Skip to content

Commit b0b2dba

Browse files
committed
Added Lowest Common Ancestor of a Binary Tree II.java
1 parent 433c62a commit b0b2dba

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode(int x) { val = x; }
8+
* }
9+
*/
10+
class Solution {
11+
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
12+
TreeNode result = lca(root, p, q);
13+
if (result == p) {
14+
return checkIfNodeExist(p, q) ? p : null;
15+
}
16+
if (result == q) {
17+
return checkIfNodeExist(q, p) ? q : null;
18+
}
19+
return result;
20+
}
21+
22+
private boolean checkIfNodeExist(TreeNode root, TreeNode target) {
23+
if (root == target) {
24+
return true;
25+
}
26+
if (root == null) {
27+
return false;
28+
}
29+
return checkIfNodeExist(root.left, target) || checkIfNodeExist(root.right, target);
30+
}
31+
32+
private TreeNode lca(TreeNode root, TreeNode p, TreeNode q) {
33+
if (root == null) {
34+
return root;
35+
}
36+
if (root == p || root == q) {
37+
return root;
38+
}
39+
TreeNode left = lca(root.left, p, q);
40+
TreeNode right = lca(root.right, p, q);
41+
if (left != null && right != null) {
42+
return root;
43+
}
44+
return left != null ? left : right;
45+
}
46+
}

0 commit comments

Comments
 (0)