Skip to content

Commit 68c9451

Browse files
committed
Lowest Common Ancestor Of A Binary Search Tree
1 parent f277d32 commit 68c9451

File tree

1 file changed

+11
-29
lines changed

1 file changed

+11
-29
lines changed
Lines changed: 11 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,13 @@
1-
// TC: O(n)
2-
// need to check all nodes
3-
// SC: O(h)
4-
// h can be O(n) in the worst case, O(log n) in the best case
1+
// TC: O(h)
2+
// h = the high of binary search tree
3+
// SC: O(1)
4+
// Doesn't require additional space
55
class Solution {
6-
public TreeNode lcaDeepestLeaves(TreeNode root) {
7-
return dfs(root, 0).node;
6+
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
7+
if (p.val < root.val && q.val < root.val)
8+
return lowestCommonAncestor(root.left, p, q);
9+
if (p.val > root.val && q.val > root.val)
10+
return lowestCommonAncestor(root.right, p, q);
11+
return root;
812
}
9-
10-
private ResultNode dfs(TreeNode node, int depth) {
11-
if (node == null) return new ResultNode(null, depth);
12-
13-
depth += 1;
14-
ResultNode leftNode = dfs(node.left, depth);
15-
ResultNode rightNode = dfs(node.right, depth);
16-
17-
if (leftNode.depth == rightNode.depth) return new ResultNode(node, leftNode.depth);
18-
else if (leftNode.depth > rightNode.depth) return leftNode;
19-
else return rightNode;
20-
}
21-
22-
private class ResultNode {
23-
private TreeNode node;
24-
private int depth;
25-
26-
ResultNode(TreeNode node, int depth) {
27-
this.node = node;
28-
this.depth = depth;
29-
}
30-
}
31-
}
13+
}

0 commit comments

Comments
 (0)