Skip to content

Commit

Permalink
Construct Binary Tree From Preorder And Inorder Traversal
Browse files Browse the repository at this point in the history
  • Loading branch information
Sunjae95 committed Aug 19, 2024
1 parent ed559ac commit 5ac3b56
Showing 1 changed file with 45 additions and 0 deletions.
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;
};

0 comments on commit 5ac3b56

Please sign in to comment.