-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathlowest-common-ancestor-of-a-binary-tree.java
51 lines (46 loc) · 1.4 KB
/
lowest-common-ancestor-of-a-binary-tree.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || root == p || root == q) return root;
TreeNode left = lowestCommonAncestor(root.left, p, q), right = lowestCommonAncestor(root.right, p, q);
if (left != null && right != null) return root;
return left == null? right : left;
}
}
/*** brute force way, but still pass **/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
while (true) {
if (checkNode(root.left, p) && checkNode(root.left, q)) {
root = root.left;
} else if (checkNode(root.right, p) && checkNode(root.right, q)) {
root = root.right;
} else {
break;
}
}
return root;
}
public boolean checkNode(TreeNode root, TreeNode p) {
if (root == null) return false;
if (root == p) return true;
return checkNode(root.left, p) || checkNode(root.right, p);
}
}