|
2 | 2 |
|
3 | 3 | import com.fishercoder.common.classes.TreeNode;
|
4 | 4 |
|
5 |
| -/**Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. |
6 |
| -
|
7 |
| - According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).” |
| 5 | +/** |
| 6 | + * 236. Lowest Common Ancestor of a Binary Tree |
| 7 | + * Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. |
| 8 | + * According to the definition of LCA on Wikipedia: |
| 9 | + * “The lowest common ancestor is defined between two nodes v and w as the lowest node in T |
| 10 | + * that has both v and w as descendants (where we allow a node to be a descendant of itself).” |
8 | 11 |
|
9 | 12 | _______3______
|
10 | 13 | / \
|
|
13 | 16 | 6 _2 0 8
|
14 | 17 | / \
|
15 | 18 | 7 4
|
16 |
| - For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.*/ |
| 19 | +
|
| 20 | + For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. |
| 21 | + Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.*/ |
| 22 | + |
17 | 23 | public class _236 {
|
18 | 24 |
|
19 |
| - /**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 |
20 |
| - result, inspired by this one: https://discuss.leetcode.com/topic/18566/my-java-solution-which-is-easy-to-understand |
21 |
| - Also, refer to my earlier drawings:http://www.fishercoder.com/2016/06/23/lowest-common-ancestor-of-a-binary-tree/ |
22 |
| - I'm really impressed with myself at that time!*/ |
| 25 | + /**We need to find TWO nodes in the tree, |
| 26 | + * so we'll have to divide and conquer this tree, |
| 27 | + * we need to have two nodes to as the intermediate result, |
| 28 | + * also, refer to my earlier drawings:http://www.fishercoder.com/2016/06/23/lowest-common-ancestor-of-a-binary-tree/ |
| 29 | + * I'm really impressed with myself at that time!*/ |
| 30 | + |
23 | 31 | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
|
24 |
| - if(root == null || root == p || root == q) return root; |
| 32 | + if (root == null || root == p || root == q) return root; |
25 | 33 | TreeNode left = lowestCommonAncestor(root.left, p, q);
|
26 | 34 | TreeNode right = lowestCommonAncestor(root.right, p, q);
|
27 |
| - if(left != null && right != null) return root; |
| 35 | + if (left != null && right != null) return root; |
28 | 36 | return left != null ? left : right;
|
29 | 37 | }
|
30 | 38 |
|
|
0 commit comments