Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Raghav2211/fe2639569c7b4817a47380b01f7a47fd to your computer and use it in GitHub Desktop.
Save Raghav2211/fe2639569c7b4817a47380b01f7a47fd to your computer and use it in GitHub Desktop.
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if( (p.val == root.val || q.val == root.val) || ( p.val < root.val && q.val > root.val)){
return root;
}
TreeNode ans = root;
if(p.val< root.val && q.val < root.val ){ //left
ans = lowestCommonAncestor(root.left,p,q);
}
else if(p.val > root.val && q.val > root.val) { // right
ans = lowestCommonAncestor(root.right,p,q);
}
return ans;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment