Created
July 27, 2020 08:50
-
-
Save RP-3/70e00e609eb06ebca74c9614f4456c8d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Definition for a binary tree node. | |
| * function TreeNode(val, left, right) { | |
| * this.val = (val===undefined ? 0 : val) | |
| * this.left = (left===undefined ? null : left) | |
| * this.right = (right===undefined ? null : right) | |
| * } | |
| */ | |
| /** | |
| * @param {number[]} inorder | |
| * @param {number[]} postorder | |
| * @return {TreeNode} | |
| */ | |
| var buildTree = function(inorder, postorder) { | |
| if(!postorder.length) return null; | |
| const idx = {}; | |
| inorder.forEach((v, i) => idx[v] = i); | |
| const build = (l, r) => { | |
| if(l > r) return null; | |
| const node = new TreeNode(postorder.pop()); | |
| if(l === r) return node; | |
| const index = idx[node.val]; | |
| node.right = build(index+1, r); | |
| node.left = build(l, index-1); | |
| return node; | |
| }; | |
| return build(0, inorder.length-1); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment