题目描述
根据一棵树的中序遍历与后序遍历构造二叉树。
注意: 你可以假设树中没有重复的元素。
例如,给出
中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:
3
/
9 20
/
15 7
求解:
与之前的 已知前序遍历序列和中序遍历序列 类似,只不过这里的根节点是由后序遍历序列的最后一个节点确定根节点
inLeft表示中序遍历序列的起始下标,inRight表示中序遍历序列的终止下标,用post_Left表示后序遍历序列的起始下标,post_Right表示后序遍历序列的终止下标,
后序遍历中,最后一个节点就是根节点root,将中序遍历的节点值和下标存到一个map中,在该map中找到根节点的位置i_Index,则可以确定相应的左子树(inLeft——iIndex-1)和右子树(i_Index+1——inRight),进而可以得到左子树的长度为(i_index-inLeft),得到左子树的长度之后,则可以进一步得到在后序遍历序列中,左子树和右子树的边界。如下图:
代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private Map<Integer,Integer> indexmap = new HashMap<>();
public TreeNode buildTree(int[] inorder, int[] postorder) {
int n = inorder.length;
for(int i = 0;i<n;i++){
indexmap.put(inorder[i],i);
}
return mybuildTree(inorder,postorder,0,n-1,0,n-1);
}
public TreeNode mybuildTree(int[] inorder,int[] postorder,int in_left,int in_right,int post_left,int post_right){
if(in_left > in_right || post_left > post_right){
return null;
}
int post_root = post_right;
int i_index = indexmap.get(postorder[post_root]);
TreeNode root = new TreeNode(postorder[post_root]);
int leftsize = i_index - in_left;
root.left = mybuildTree(inorder,postorder,in_left,i_index-1,post_left,post_left+leftsize-1);
root.right = mybuildTree(inorder,postorder,i_index+1,in_right,post_left+leftsize,post_right-1);
return root;
}
}