Skip to content

Instantly share code, notes, and snippets.

@criskgl
Created November 17, 2019 11:18
Show Gist options
  • Save criskgl/1c5d5968879ce608db7614f9f76331a3 to your computer and use it in GitHub Desktop.
Save criskgl/1c5d5968879ce608db7614f9f76331a3 to your computer and use it in GitHub Desktop.
class Solution {
TreeNode answer;
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
this.answer = new TreeNode(-1);
LCA(root, p, q);
return this.answer;
}
public boolean LCA(TreeNode root, TreeNode p, TreeNode q){
if(root.right == null && root.left == null){//leaf
if(root.val == p.val || root.val == q.val) return true;
return false;
}
boolean ansL = false;
boolean ansR = false;
if(root.left != null){//check right if possible
ansL = LCA(root.left, p, q);
}
if(root.right != null){//check left if possible
ansR = LCA(root.right, p, q);
}
/*check if root contains wanted value and any of
left or right branches contains other val*/
if((root.val == p.val || root.val == q.val) && (ansL || ansR)){
this.answer = root;
}
/*Check if R and L descedants of node contain values wanted*/
if(ansL && ansR){
this.answer = root;
}
if(root.val == p.val || root.val == q.val) {
return true;
}
return (ansL || ansR);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment