Skip to content

Commit 0c6f969

Browse files
committed
2. Lowest Common Ancestor of a Binary Search Tree
1 parent c8d452b commit 0c6f969

File tree

1 file changed

+31
-0
lines changed
  • lowest-common-ancestor-of-a-binary-search-tree

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* @description
3+
* bfs, dfs와 같은 순회 방법과 treeNode 구조에 child가 아닌 parent라는 속성을 부여해 부모찾기를 아이디어로 접근
4+
* 하지만 모든 노드를 순회해야하고 p와 q가 속한지점과 둘이 포함하는 관계인지를 중점으로 문제에 접근함
5+
* 그 결과 postOrder를 생각하게 되어 문제 풀이
6+
*
7+
* n = length of total treeNode
8+
* time complexity: O(n)
9+
* space complexity: O(n)
10+
*/
11+
var lowestCommonAncestor = function (root, p, q) {
12+
let answer = null;
13+
14+
const postOrder = (tree) => {
15+
if (tree === null) return [false, false];
16+
17+
const [hasLeftP, hasLeftQ] = postOrder(tree.left);
18+
const [hasRightP, hasRightQ] = postOrder(tree.right);
19+
20+
const hasP = hasLeftP || hasRightP || tree.val === p.val;
21+
const hasQ = hasLeftQ || hasRightQ || tree.val === q.val;
22+
23+
if (hasP && hasQ && answer === null) answer = tree;
24+
25+
return [hasP, hasQ];
26+
};
27+
28+
postOrder(root);
29+
30+
return answer;
31+
};

0 commit comments

Comments
 (0)