Thoughts on leetcode 236
Traverse the tree in a depth first manner. The moment you encounter either of the nodes p
or q
, return some boolean flag. The flag helps to determine if we found the required nodes in any of the paths. The least common ancestor would then be the node for which both the subtree recursions return a True
flag. It can also be the node which itself is one of p
or q
and for which one of the subtree recursions returns a True
flag. (the reason why we create the variable cur)
Solution for leetcode 236
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
class Solution {
TreeNode ans = null;
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
found(root, p, q);
return ans;
}
public boolean found(TreeNode root, TreeNode p, TreeNode q){
if(root == null){
return false;
}
//check if the current node is the target node
int cur = (root == p || root == q) ? 1 : 0;
//check if the left and right branches
int left = found(root.left, p, q) ? 1 : 0;
int right = found(root.right, p, q) ? 1 : 0;
if(cur + left + right == 2){
ans = root;
}
return (cur + left + right) == 1;
}
}