Find lowest common ancestor in Binary Search Tree

后端 未结 6 1188
一生所求
一生所求 2021-02-10 13:57

I\'ve got the following code to find the lowest common ancestor (the lowest node that has both a and b as descendants):

public static Node LCA(Node root, Node a,          


        
6条回答
  •  轮回少年
    2021-02-10 14:31

    If the IData of root is different from both, a's and b's, but one of root's children has the same IData as either of the two, you return root, but by your definition, you should return the child if both nodes are in the same subtree. Since you also want to check that both nodes actually are in the tree, that check must be performed before any return.

    public static Node LCA(Node root, Node a, Node b)
    {
        if (root == null) return null;
        // what if a == null or b == null ?
        Node small, large, current = root;
        if (a.IData < b.IData)
        {
            small = a;
            large = b;
        }
        else
        {
            small = b;
            large = a;
        }
        if (large.IData < current.IData)
        {
            do
            {
                current = current.LeftChild;
            }while(current != null && large.IData < current.IData);
            if (current == null) return null;
            if (current.IData < small.IData) return LCA(current,small,large);
            // if we get here, current has the same IData as one of the two, the two are
            // in different subtrees, or not both are in the tree
            if (contains(current,small) && contains(current,large)) return current;
            // at least one isn't in the tree, return null
            return null;
        }
        else if (current.IData < small.IData)
        {
            // the symmetric case, too lazy to type it out
        }
        else // Not both in the same subtree
        {
            if (contains(current,small) && contains(current,large)) return current;
        }
        return null; // at least one not in tree
    }
    
    public static bool contains(Node root, Node target)
    {
        if (root == null) return false;
        if (root.IData == target.IData) return true;
        if (root.IData < target.IData) return contains(root.RightChild,target);
        return contains(root.LeftChild,target);
    }
    

提交回复
热议问题