Created
November 17, 2019 11:18
-
-
Save criskgl/1c5d5968879ce608db7614f9f76331a3 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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