Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Construct Binary Tree from Preorder and Inorder Traversal #39

Open
kokocan12 opened this issue Jun 22, 2022 · 0 comments
Open

Construct Binary Tree from Preorder and Inorder Traversal #39

kokocan12 opened this issue Jun 22, 2022 · 0 comments

Comments

@kokocan12
Copy link
Owner

Problem

When preorder, and inorder values are given, where each element is node's value, contruct binary tree.
Each element in the preorder and inorder is unique.

image

Approach

Preorder is traversal that move head first then move to left, right.
On the other hand, Inorder is traversal that move left first then move to head, right.

We can get the head element of the tree by picking first item of preorder.
Then, we can divide inorder into left side and right side, because we know what head value is.
Finally, we can also divide preorder, because we know the length of the left-side and the length of the right-side.

preorder = [HEAD, [LEFTSIDE], [RIGHTSIDE]]
inorder = [[LEFTSIDE], HEAD, [RIGHTSIDE]]

The code is below.

function build(preorder, inorder) {
    {
        if(preorder.length === 0) return null;
    
        const head = preorder[0];
        const root = new TreeNode(head);
    
        const headIndex = inorder.indexOf(head);

        const inorderLeft = inorder.slice(0, headIndex);
        const inorderRight = inorder.slice(headIndex+1, inorder.length);
        
    
        const preorderLeft = preorder.slice(1, 1+inorderLeft.length);
        const preorderRight = preorder.slice(1+inorderLeft.length, inorder.length);
        
        
        root.left = build(preorderLeft, inorderLeft);
        root.right = build(preorderRight, inorderRight);
        
        return root;
    }
    
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant