Binary Search Tree : Lowest Common Ancestor

  • + 0 comments

    here another java solution, but this solution destroys the tree lol

    	public static Node lca(Node root, int v1, int v2) {
            if(root==null) {
             return null; 
            }
            if(root.data==v1||root.data==v2) {
             return  root; 
            }
            if(root.left==null&&root.right==null) {
              if(root.data==v1||root.data==v2) {
                  return root; 
              }
                  return null;  
            }
           root.left = lca(root.left,v1,v2);
           root.right =  lca(root.right,v1,v2); 
            if(root.left==null||root.right==null) {
                if(root.left!=null) {
                  return root.left; 
                }
                 return root.right; 
            }
    
            return root; 
        }