Find Lowest common ancestor of bst
Page 1 of 1
Find Lowest common ancestor of bst
public static TreeNode findancestor(TreeNode root, TreeNode n1, TreeNode n2){
if(cover(root.left,n1)&&cover(root.left,n2))
return findancestor(root.left,n1,n2);
if(cover(root.right,n1)&&cover(root.right,n2))
return findancestor(root.right,n1,n2);
return root;
}
public boolean cover(TreeNode root, TreeNode n1){
if(root==null)
return false;
else if(root==n1)
return true;
return cover(root.left,n1)||cover(root.right,n1);
}
if(cover(root.left,n1)&&cover(root.left,n2))
return findancestor(root.left,n1,n2);
if(cover(root.right,n1)&&cover(root.right,n2))
return findancestor(root.right,n1,n2);
return root;
}
public boolean cover(TreeNode root, TreeNode n1){
if(root==null)
return false;
else if(root==n1)
return true;
return cover(root.left,n1)||cover(root.right,n1);
}
Page 1 of 1
Permissions in this forum:
You cannot reply to topics in this forum