根据一棵树的中序遍历与后序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:
3
/
9 20
/
15 7
AC代码:
class Solution {
int[] postorder;
HashMap<Integer,Integer> map = new HashMap();
public TreeNode buildTree(int[] inorder, int[] postorder) {
this.postorder = postorder;
for(int i=0;i<inorder.length;i++){
//System.out.println(inorder[i]);
map.put(inorder[i],i);
}
int N = inorder.length;
return recur(N-1,0,N-1);
}
//第一个参数root是根在后序序列的位置,left,right是在中序序列中的位置,
public TreeNode recur(int root,int left,int right){
if(left > right) return null;
//根在中序序列的位置
int i = map.get(postorder[root]);
TreeNode node = new TreeNode(postorder[root]);
//右子树
node.right = recur(root-1,i+1,right);
int rightLen = right-i;
node.left = recur(root-(right-i)-1,left,i-1);
return node;
}
}
思考:为什么recur可以构建出一棵树呢?
首先,我们要知道:要构建一棵树,首先要构建根节点,再构建它的左右子树(在子树中也是如此,符合递归的应用场景)(给先序和中序就先构建左子树,给后序和中序就先构建右子树)。以后序为例,在后续序列中的任何局部子树都符合左右根的遍历顺序,所以后续序列的最后一个数必然是根的值,上一个节点必然是右子树根的值,至于左子树根可以有前两者的位置得到。