-
Notifications
You must be signed in to change notification settings - Fork 123
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Construct Binary Tree From Preorder And Inorder Traversal
- Loading branch information
Showing
1 changed file
with
45 additions
and
0 deletions.
There are no files selected for viewing
45 changes: 45 additions & 0 deletions
45
construct-binary-tree-from-preorder-and-inorder-traversal/sunjae95.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
/** | ||
* @description | ||
* time complexity: O(n^2) | ||
* space complexity: O(n) | ||
* | ||
* brainstorming: | ||
* stack, Drawing a graph | ||
* | ||
* strategy: | ||
* discover the rules | ||
* leftStack = left create , rightStack = right create | ||
*/ | ||
var buildTree = function (preorder, inorder) { | ||
let answer = null; | ||
let pointer = 0; | ||
|
||
const leftStack = []; | ||
const rightStack = []; | ||
|
||
preorder.forEach((val, i) => { | ||
const node = new TreeNode(val); | ||
|
||
if (i === 0) answer = node; | ||
|
||
const leftLen = leftStack.length; | ||
const rightLen = rightStack.length; | ||
|
||
if (leftLen && rightLen) { | ||
if (leftStack[leftLen - 1].left) rightStack[rightLen - 1].right = node; | ||
else leftStack[leftLen - 1].left = node; | ||
} | ||
if (leftLen && !rightLen) leftStack[leftLen - 1].left = node; | ||
if (!leftLen && rightLen) rightStack[rightLen - 1].right = node; | ||
|
||
leftStack.push(node); | ||
|
||
while (leftStack.length && pointer < inorder.length) { | ||
if (leftStack[leftStack.length - 1].val !== inorder[pointer]) break; | ||
rightStack.push(leftStack.pop()); | ||
pointer++; | ||
} | ||
}); | ||
|
||
return answer; | ||
}; |