Created
March 30, 2022 12:03
-
-
Save Raghav2211/fe2639569c7b4817a47380b01f7a47fd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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