|
| 1 | +/* |
| 2 | +Construct Binary Tree from Preorder and Inorder Traversal |
| 3 | +https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ |
| 4 | +
|
| 5 | +Given preorder and inorder traversal of a tree, construct the binary tree. |
| 6 | +
|
| 7 | +Note: |
| 8 | +You may assume that duplicates do not exist in the tree. |
| 9 | +
|
| 10 | +For example, given |
| 11 | +
|
| 12 | +preorder = [3,9,20,15,7] |
| 13 | +inorder = [9,3,15,20,7] |
| 14 | +Return the following binary tree: |
| 15 | +
|
| 16 | + 3 |
| 17 | + / \ |
| 18 | + 9 20 |
| 19 | + / \ |
| 20 | + 15 7 |
| 21 | +*/ |
| 22 | + |
| 23 | +/** |
| 24 | + * Definition for a binary tree node. |
| 25 | + * function TreeNode(val) { |
| 26 | + * this.val = val; |
| 27 | + * this.left = this.right = null; |
| 28 | + * } |
| 29 | + */ |
| 30 | +/** |
| 31 | + * @param {number[]} preorder |
| 32 | + * @param {number[]} inorder |
| 33 | + * @return {TreeNode} |
| 34 | + */ |
| 35 | +var buildTree = function(preorder, inorder) { |
| 36 | + if(preorder === null || inorder === null || preorder.length !== inorder.length) |
| 37 | + return nil; |
| 38 | + |
| 39 | + return buildTreeAux(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1); |
| 40 | +}; |
| 41 | + |
| 42 | +var buildTreeAux = function(preorder, pl, ph, inorder, il, ih) { |
| 43 | + if(pl > ph || il > ih) |
| 44 | + return null; |
| 45 | + |
| 46 | + const rootValue = preorder[pl]; |
| 47 | + var countElementsLeft = 0; |
| 48 | + while(inorder[il + countElementsLeft] !== rootValue) { |
| 49 | + countElementsLeft++; |
| 50 | + } |
| 51 | + |
| 52 | + var ret = new TreeNode(rootValue); |
| 53 | + ret.left = buildTreeAux(preorder, pl + 1, pl + countElementsLeft, inorder, il, il + countElementsLeft - 1); |
| 54 | + ret.right = buildTreeAux(preorder, pl + countElementsLeft + 1, ph, inorder, il + countElementsLeft + 1, ih); |
| 55 | + |
| 56 | + return ret; |
| 57 | +} |
| 58 | + |
| 59 | +var TreeNode = function(val) { |
| 60 | + this.val = val; |
| 61 | + this.left = this.right = null; |
| 62 | +} |
| 63 | + |
| 64 | +console.log( |
| 65 | + buildTree( |
| 66 | + [3,9,20,15,7], |
| 67 | + [9,3,15,20,7] |
| 68 | + ) |
| 69 | +); |
| 70 | + |
| 71 | +module.exports.main = main |
0 commit comments