File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed
lowest-common-ancestor-of-a-binary-search-tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change 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+ } ;
You can’t perform that action at this time.
0 commit comments