问题描述
根据一棵树的中序遍历与后序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
思路
后序遍历的结构是:左、右、中。
中序遍历的结构是:左、中、右。
所以后序遍历的最后一个结点肯定是根结点。根据这个从中序遍历找到左右子树,分别递归的建立左子树和右子树即可。
方法一
Java版
class Solution {
Map<Integer, Integer> map = new HashMap<>();
public TreeNode buildTree(int[] inorder, int[] postorder) {
if(inorder.length == 0) return null;
for(int i = 0; i < inorder.length; i++) map.put(inorder[i],i);
return buildTree(inorder,postorder,0,inorder.length-1,0,postorder.length-1);
}
private TreeNode buildTree(int[] inorder, int[] postorder, int inLeft,int inRight,int postLeft,int postRight){
if(inLeft>inRight) return null;
TreeNode root = new TreeNode(postorder[postRight]);
int rootIndex = map.get(postorder[postRight]);
System.out.println(rootIndex);
root.left = buildTree(inorder,postorder,inLeft,rootIndex-1,postLeft,postLeft+rootIndex-inLeft-1);
root.right = buildTree(inorder,postorder,rootIndex+1,inRight,postLeft+rootIndex-inLeft,postRight-1);
return root;
}
}