Find lowest common ancestor in Binary Search Tree

后端 未结 6 1116
一生所求
一生所求 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:17

    public static Node LCA(Node root, Node a, Node b)
    {
    
        if (root == null)
            return null;
    
        if (root.IData > a.IData && root.IData > b.IData)
            return LCA(root.LeftChild, a, b);
        if (root.IData < a.IData && root.IData < b.IData)
            return LCA(root.RightChild, a, b);
    
        return root;
    }
    

提交回复
热议问题