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)
34
45/**
56 * Definition for a binary tree node.
1617 * @return {TreeNode }
1718 */
1819var 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+ }
4423
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 ) ;
5326 }
5427
55- return answer ;
28+ return root ;
5629} ;
You can’t perform that action at this time.
0 commit comments