二进制搜索树的两个节点之间的距离

时间:2017-11-24 20:30:03

标签: algorithm data-structures binary-search-tree

我是Binary Tree Search Tree的新手。使用递归,我找到二元搜索树的两个节点之间的距离。如果有更好的方法。请分享您的建议。这将有助于我了解更多信息。

 boolean found=false;

int distanceBetweenTwoNodeOfBST(Node node,int firstElement,int secondElement){

    if(firstElement==secondElement){
        return 0;
    }
    if(node==null){
        return 0;
    }else{
        if(node.element==firstElement || node.element==secondElement){
            int leftDis=distanceBetweenTwoNodeOfBST(node.left, firstElement, secondElement);
            int rightDis=distanceBetweenTwoNodeOfBST(node.right, firstElement, secondElement);

            if(leftDis>0 || rightDis>0){
                found=true;
            }

    if(leftDis> 0){
        --leftDis;
    }

    if(rightDis>0){
        --rightDis;
    }

            return 1+leftDis+rightDis;
        }

        int firstElementCount=distanceBetweenTwoNodeOfBST(node.left, firstElement, secondElement); // Going to left Subtree
        int secondELementCount=distanceBetweenTwoNodeOfBST(node.right, firstElement, secondElement); // Going to right Subtree
        if(firstElementCount>0 && secondELementCount>0){ // It means Least Common Ancestor is found
            found=true;
            return firstElementCount+secondELementCount;
        }else if(firstElementCount>0) {
            if(found){
                return firstElementCount;
            }else
            return firstElementCount+1;
        }else if(secondELementCount>0){
            if(found) return secondELementCount;
            else return secondELementCount+1;
        }else{
            return 0;
        }

    }

}

注意 - :如果还有其他更好的方法,请分享建议。我是新手。

0 个答案:

没有答案