|
| 1 | +/** |
| 2 | + * 889. Construct Binary Tree from Preorder and Postorder Traversal |
| 3 | + * https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Given two integer arrays, preorder and postorder where preorder is the preorder traversal of a |
| 7 | + * binary tree of distinct values and postorder is the postorder traversal of the same tree, |
| 8 | + * reconstruct and return the binary tree. |
| 9 | + * |
| 10 | + * If there exist multiple answers, you can return any of them. |
| 11 | + */ |
| 12 | + |
| 13 | +/** |
| 14 | + * Definition for a binary tree node. |
| 15 | + * function TreeNode(val, left, right) { |
| 16 | + * this.val = (val===undefined ? 0 : val) |
| 17 | + * this.left = (left===undefined ? null : left) |
| 18 | + * this.right = (right===undefined ? null : right) |
| 19 | + * } |
| 20 | + */ |
| 21 | +/** |
| 22 | + * @param {number[]} preorder |
| 23 | + * @param {number[]} postorder |
| 24 | + * @return {TreeNode} |
| 25 | + */ |
| 26 | +var constructFromPrePost = function(preorder, postorder) { |
| 27 | + if (!preorder.length) return null; |
| 28 | + |
| 29 | + const root = new TreeNode(preorder[0]); |
| 30 | + if (preorder.length === 1) return root; |
| 31 | + |
| 32 | + const leftSize = postorder.indexOf(preorder[1]) + 1; |
| 33 | + root.left = constructFromPrePost( |
| 34 | + preorder.slice(1, leftSize + 1), |
| 35 | + postorder.slice(0, leftSize) |
| 36 | + ); |
| 37 | + root.right = constructFromPrePost( |
| 38 | + preorder.slice(leftSize + 1), |
| 39 | + postorder.slice(leftSize, -1) |
| 40 | + ); |
| 41 | + |
| 42 | + return root; |
| 43 | +}; |
0 commit comments