Skip to content

Commit 14ab484

Browse files
committedAug 2, 2017
edit 236
1 parent 507ca82 commit 14ab484

File tree

1 file changed

+18
-10
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+18
-10
lines changed
 

‎src/main/java/com/fishercoder/solutions/_236.java

+18-10
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,12 @@
22

33
import com.fishercoder.common.classes.TreeNode;
44

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).”
811
912
_______3______
1013
/ \
@@ -13,18 +16,23 @@
1316
6 _2 0 8
1417
/ \
1518
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+
1723
public class _236 {
1824

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+
2331
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;
2533
TreeNode left = lowestCommonAncestor(root.left, p, q);
2634
TreeNode right = lowestCommonAncestor(root.right, p, q);
27-
if(left != null && right != null) return root;
35+
if (left != null && right != null) return root;
2836
return left != null ? left : right;
2937
}
3038

0 commit comments

Comments
 (0)