Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Code assembles a Binary Tree using depth first traversal, taking in the inorder and postorder of the tree to create it
- //Definition of a Tree Node
- //function TreeNode(val) {
- // this.val = val;
- // this.right = this.left = null;
- //}
- const buildTree = function(inorder, postorder) {
- let hashmap = [];
- let post_index = postorder.length - 1;
- let in_left = 0;
- let in_right = postorder.length - 1;
- for(let val in inorder) {
- hashmap.push(inorder[val]);
- return helper(in_left, in_right);
- function helper(in_left, in_right) {
- if(in_left > in_right) return null;
- //Find the value of the node, create the new node
- let root_val = postorder[post_index];
- let root = new TreeNode(root_val);
- let index = hashmap.indexOf(root_val);
- //Recursively use the helper function to add nodes to the tree.
- //Base case above will return null because the length of the array won't exist
- post_index--;
- //right first because of post order
- root.right = helper(index + 1, in_right);
- root.left = helper(in_left, index - 1);
- //Root returns the first root so we can observe the tree
- return root;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement