File tree Expand file tree Collapse file tree 1 file changed +11
-29
lines changed
lowest-common-ancestor-of-a-binary-search-tree Expand file tree Collapse file tree 1 file changed +11
-29
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
1
+ // TC: O(h )
2
+ // h = the high of binary search tree
3
+ // SC: O(1 )
4
+ // Doesn't require additional space
5
5
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 ;
8
12
}
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
+ }
You can’t perform that action at this time.
0 commit comments