Skip to content

Commit 556a228

Browse files
committed
Lowest Common Ancestor Of A Binary Search Tree
1 parent 62fca0d commit 556a228

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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
5+
class Solution {
6+
public TreeNode lcaDeepestLeaves(TreeNode root) {
7+
return dfs(root, 0).node;
8+
}
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+
}

0 commit comments

Comments
 (0)