We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
出处 LeetCode 算法第106题 根据一棵树的中序遍历与后序遍历构造二叉树。 注意: 你可以假设树中没有重复的元素。 例如,给出 中序遍历 inorder = [9,3,15,20,7] 后序遍历 postorder = [9,15,7,20,3] 返回如下的二叉树: 3 / \ 9 20 / \ 15 7
出处 LeetCode 算法第106题
根据一棵树的中序遍历与后序遍历构造二叉树。
注意: 你可以假设树中没有重复的元素。
例如,给出
中序遍历 inorder = [9,3,15,20,7] 后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:
3 / \ 9 20 / \ 15 7
通过观察,可以发现后序遍历的最后一个元素为root,找出这个元素在中序遍历中的位置,这个位置前的元素即为左子树的元素,这个元素后的元素为右子树的元素。通过递归,得出整个树
function TreeNode(val) { this.val = val; this.left = this.right = null; } /** * @param {number[]} inorder * @param {number[]} postorder * @return {TreeNode} */ function helper(inorder, postorder) { if (inorder.length == 0 || postorder.length == 0) { return null; } var length = postorder.length; var rootVal = postorder[length - 1]; var index = inorder.indexOf(rootVal); var inorderLeft = inorder.slice(0, index); var inorderRight = inorder.slice(index + 1); var postorderLeft = postorder.slice(0, index); var postorderRight = postorder.slice(index, -1); var root = new TreeNode(rootVal); if (inorderLeft.length > 0) { root.left = helper(inorderLeft, postorderLeft); } if (postorderRight.length > 0) { root.right = helper(inorderRight, postorderRight); } return root; } var buildTree = function (inorder, postorder) { if (inorder.length == 0 || postorder.length == 0) { return []; } return helper(inorder, postorder); }; console.log(buildTree([9, 3, 15, 20, 7], [9, 15, 7, 20, 3]))
The text was updated successfully, but these errors were encountered:
No branches or pull requests
习题
思路
通过观察,可以发现后序遍历的最后一个元素为root,找出这个元素在中序遍历中的位置,这个位置前的元素即为左子树的元素,这个元素后的元素为右子树的元素。通过递归,得出整个树
解答
The text was updated successfully, but these errors were encountered: