File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed
lowest-common-ancestor-of-a-binary-search-tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments