-
Notifications
You must be signed in to change notification settings - Fork 15
/
lowest-common-ancestor.java
91 lines (79 loc) · 2.34 KB
/
lowest-common-ancestor.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of the binary search tree.
* @param A and B: two nodes in a Binary.
* @return: Return the least common ancestor(LCA) of the two nodes.
*/
// top-down recursion, balanced tree: O(n).
// unbalanced tree: O(n^2)
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode A, TreeNode B) {
// write your code here
if (root == A || root == B) {
return root;
}
boolean aInLeft = containsNode(root.left, A);
boolean bInLeft = containsNode(root.left, B);
if (aInLeft && !bInLeft || !aInLeft && bInLeft) {
return root;
}
if (aInLeft) {
return lowestCommonAncestor(root.left, A, B);
} else {
return lowestCommonAncestor(root.right, A, B);
}
}
public boolean containsNode(TreeNode parent, TreeNode node) {
if (parent == null) {
return node == null;
}
if (parent == node) {
return true;
}
return containsNode(parent.left, node) || containsNode(parent.right, node);
}
}
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of the binary search tree.
* @param A and B: two nodes in a Binary.
* @return: Return the least common ancestor(LCA) of the two nodes.
*/
// bottom-up recursion: O(n)
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode A, TreeNode B) {
// write your code here
if (root == null) {
return null;
}
if (root == A || root == B) {
return root;
}
TreeNode left = lowestCommonAncestor(root.left, A, B);
TreeNode right = lowestCommonAncestor(root.right, A, B);
if (left != null && right != null) {
return root;
}
return left != null? left : right;
}
}