File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed
construct-binary-tree-from-preorder-and-inorder-traversal Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @description
3+ * time complexity: O(n^2)
4+ * space complexity: O(n)
5+ *
6+ * brainstorming:
7+ * stack, Drawing a graph
8+ *
9+ * strategy:
10+ * discover the rules
11+ * leftStack = left create , rightStack = right create
12+ */
13+ var buildTree = function ( preorder , inorder ) {
14+ let answer = null ;
15+ let pointer = 0 ;
16+
17+ const leftStack = [ ] ;
18+ const rightStack = [ ] ;
19+
20+ preorder . forEach ( ( val , i ) => {
21+ const node = new TreeNode ( val ) ;
22+
23+ if ( i === 0 ) answer = node ;
24+
25+ const leftLen = leftStack . length ;
26+ const rightLen = rightStack . length ;
27+
28+ if ( leftLen && rightLen ) {
29+ if ( leftStack [ leftLen - 1 ] . left ) rightStack [ rightLen - 1 ] . right = node ;
30+ else leftStack [ leftLen - 1 ] . left = node ;
31+ }
32+ if ( leftLen && ! rightLen ) leftStack [ leftLen - 1 ] . left = node ;
33+ if ( ! leftLen && rightLen ) rightStack [ rightLen - 1 ] . right = node ;
34+
35+ leftStack . push ( node ) ;
36+
37+ while ( leftStack . length && pointer < inorder . length ) {
38+ if ( leftStack [ leftStack . length - 1 ] . val !== inorder [ pointer ] ) break ;
39+ rightStack . push ( leftStack . pop ( ) ) ;
40+ pointer ++ ;
41+ }
42+ } ) ;
43+
44+ return answer ;
45+ } ;
You can’t perform that action at this time.
0 commit comments