Skip to content

Commit cb66901

Browse files
MEDIUM/src/medium/LowestCommonAncestorOfABinaryTree.java
1 parent 6363289 commit cb66901

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package medium;
2+
3+
import classes.TreeNode;
4+
5+
public class LowestCommonAncestorOfABinaryTree {
6+
//we need to find TWO nodes in the tree, so we'll have to divide and conquer this tree, we need to have two nodes to as the intermediate
7+
//result, inspired by this one: https://discuss.leetcode.com/topic/18566/my-java-solution-which-is-easy-to-understand
8+
//Also, refer to my earlier drawings:http://www.fishercoder.com/2016/06/23/lowest-common-ancestor-of-a-binary-tree/
9+
//I'm really impressed with myself at that time!
10+
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
11+
if(root == null || root == p || root == q) return root;
12+
TreeNode left = lowestCommonAncestor(root.left, p, q);
13+
TreeNode right = lowestCommonAncestor(root.right, p, q);
14+
if(left != null && right != null) return root;
15+
return left != null ? left : right;
16+
}
17+
18+
}

0 commit comments

Comments
 (0)