来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
给定两个整数数组 inorder 和 postorder ,其中 inorder 是二叉树的中序遍历, postorder 是同一棵树的后序遍历,请你构造并返回这颗 二叉树 。
解答
通过中序遍历数组和后序遍历数组得到二叉树:
- 原理跟 38 题一致
后序遍历数组 pop 用于初始化节点,中序遍历数组用于判断是否有子树
/*** 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 (inorder.length && postorder.length) {const rootVal = postorder.pop();const rootIndex = inorder.indexOf(rootVal);const root = new TreeNode(rootVal);root.right = buildTree(inorder.slice(rootIndex + 1),postorder);root.left = buildTree(inorder.slice(0, rootIndex),postorder);return root;} else {return null;}};
