File tree Expand file tree Collapse file tree 1 file changed +9
-36
lines changed
lowest-common-ancestor-of-a-binary-search-tree Expand file tree Collapse file tree 1 file changed +9
-36
lines changed Original file line number Diff line number Diff line change 1
- // Time complexity: O(logn)
2
- // Space complexity: O(logn)
1
+ // h : height of BST
2
+ // Time complexity: O(h)
3
+ // Space complexity: O(h)
3
4
4
5
/**
5
6
* Definition for a binary tree node.
16
17
* @return {TreeNode }
17
18
*/
18
19
var lowestCommonAncestor = function ( root , p , q ) {
19
- // 1. 각자 부모 리스트 완성
20
- const search = ( target , parent ) => {
21
- const dfs = ( current ) => {
22
- if ( target . val > current . val ) {
23
- dfs ( current . right ) ;
24
- }
25
-
26
- if ( target . val < current . val ) {
27
- dfs ( current . left ) ;
28
- }
29
-
30
- parent . push ( current ) ;
31
- } ;
32
-
33
- dfs ( root ) ;
34
- } ;
35
-
36
- const parentP = [ ] ;
37
- const parentQ = [ ] ;
38
-
39
- search ( p , parentP ) ;
40
- search ( q , parentQ ) ;
41
-
42
- // 2. 공통 부모 탐색
43
- let answer = null ;
20
+ if ( root . val < p . val && root . val < q . val && root . left ) {
21
+ return lowestCommonAncestor ( root . right , p , q ) ;
22
+ }
44
23
45
- while (
46
- parentP . at ( - 1 ) &&
47
- parentQ . at ( - 1 ) &&
48
- parentP . at ( - 1 ) . val === parentQ . at ( - 1 ) . val
49
- ) {
50
- answer = parentP . at ( - 1 ) ;
51
- parentP . pop ( ) ;
52
- parentQ . pop ( ) ;
24
+ if ( root . val > p . val && root . val > q . val && root . right ) {
25
+ return lowestCommonAncestor ( root . left , p , q ) ;
53
26
}
54
27
55
- return answer ;
28
+ return root ;
56
29
} ;
You can’t perform that action at this time.
0 commit comments