题目
根据一棵树的中序遍历与后序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
解题思路
“后序找根,划分左右”。具体的,通过后序遍历我们可以找到root,根据root我们可以在中序遍历中找到当前root对应的左右子树,再递归对当前root的左右子树进行构造。所以构建二叉树的问题流程就是:
1)找到各个子树的根节点 root;
2)构建该根节点的左子树;
3)构建该根节点的右子树。
(类似题目:105. 从前序与中序遍历序列构造二叉树)
代码
Python代码如下:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
if not inorder or not postorder:
return None
root = TreeNode(postorder[-1])
root_idx = inorder.index(postorder[-1])
# 递归地构建左子树
root.left = self.buildTree(inorder[:root_idx], postorder[:root_idx])
# 递归地构建右子树
root.right = self.buildTree(inorder[root_idx+1:], postorder[root_idx:-1])
return root
Java代码如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode myBuildTree(int[] inorder, int[] postorder, int inleft, int inright, int postleft, int postright, Map<Integer, Integer> map){
if(inleft > inright || postleft > postright){
return null;
}
TreeNode root = new TreeNode(postorder[postright]);
int root_idx = map.get(postorder[postright]);
root.left = myBuildTree(inorder, postorder, inleft, root_idx-1, postleft, root_idx-inleft+postleft-1, map);
root.right = myBuildTree(inorder, postorder, root_idx+1, inright, root_idx-inleft+postleft, postright-1, map);
return root;
}
public TreeNode buildTree(int[] inorder, int[] postorder) {
int n = inorder.length;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i=0; i<n; i++){
map.put(inorder[i], i);
}
return myBuildTree(inorder, postorder, 0, n-1, 0, n-1, map);
}
}