File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed
lowest-common-ancestor-of-a-binary-search-tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Definition for a binary tree node.
3+ * class TreeNode {
4+ * val: number
5+ * left: TreeNode | null
6+ * right: TreeNode | null
7+ * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
8+ * this.val = (val===undefined ? 0 : val)
9+ * this.left = (left===undefined ? null : left)
10+ * this.right = (right===undefined ? null : right)
11+ * }
12+ * }
13+ */
14+ /**
15+ * BST 이진트리에 두 노드가 주어졌을 때, 근접한 부모 찾기
16+ * 알고리즘 복잡도
17+ * - 시간 복잡도: O(n)
18+ * - 공간 복잡도: O(n)
19+ * @param root
20+ * @param p
21+ * @param q
22+ */
23+ function lowestCommonAncestor ( root : TreeNode | null , p : TreeNode | null , q : TreeNode | null ) : TreeNode | null {
24+ if ( root === null || p === null || q === null ) return null ;
25+
26+ if ( p . val < root . val && q . val < root . val ) {
27+ return lowestCommonAncestor ( root . left , p , q )
28+ } else if ( p . val > root . val && q . val > root . val ) {
29+ return lowestCommonAncestor ( root . right , p , q )
30+ } else {
31+ // 현재 노드가 양쪽 방향으로 있거나 현재 노드가 p, q인 경우
32+ return root
33+ }
34+ }
You can’t perform that action at this time.
0 commit comments