File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed
lowest-common-ancestor-of-a-binary-search-tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time complexity: O(logn)
2
+ // Space complexity: O(logn)
3
+
4
+ /**
5
+ * Definition for a binary tree node.
6
+ * function TreeNode(val) {
7
+ * this.val = val;
8
+ * this.left = this.right = null;
9
+ * }
10
+ */
11
+
12
+ /**
13
+ * @param {TreeNode } root
14
+ * @param {TreeNode } p
15
+ * @param {TreeNode } q
16
+ * @return {TreeNode }
17
+ */
18
+ 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 ;
44
+
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 ( ) ;
53
+ }
54
+
55
+ return answer ;
56
+ } ;
You can’t perform that action at this time.
0 commit comments