Find lowest common ancestor in Binary Search Tree

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

    Here you go:

    Console.WriteLine("\n\n /* Lowest Common Ancestor */");
    int v1 = 4, v2 = 8;
    Node lca = LCA(Root, v1, v2);
    Console.WriteLine("LCA of {0} and {1} is: {2}", v1, v2, (lca != null ? lca.Data.ToString() : "No LCA Found"));
    
    
    public static Node LCA(Node root, int v1, int v2)
    {
            if (root == null)
                return null;
    
            if (root.Data > v1 && root.Data > v2)
                return LCA(root.Left, v1, v2);
            else if (root.Data < v1 && root.Data < v2)
                return LCA(root.Right, v1, v2);
            else
                return root;
    }
    

提交回复
热议问题