一、题目
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
二、题目大意
根据二叉树的中序遍历和后序遍历构造一颗二叉树。
三、解题思路
这道题需要从这两个遍历数组找出规律:
9 3 15 20 7
left root right
9 15 7 20 3
left right root
后序遍历数组的最后一位为根节点,然后通过当前的根节点可以将中序遍历数组分成左右两个子树的中序遍历数组,再根据该下标将后序遍历数组也分成左右子树的后序遍历数组,递归得出结果。
四、代码实现
const buildTree = (inorder, postorder) => {
if (!inorder) {
return null
}
const val = postorder.pop()
const root = new TreeNode(val)
const index = inorder.indexOf(val)
root.left = buildTree(inorder.slice(0, index), postorder.slice(0, index))
root.right = buildTree(inorder.slice(index + 1), postorder.slice(index))
return root
}
如果本文对您有帮助,欢迎关注微信公众号,为您推送更多大前端相关的内容, 欢迎留言讨论,ε=ε=ε=┏(゜ロ゜;)┛。
您还可以在这些地方找到我: