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
即根据中序遍历和后序遍历的结果构造树.
前提:没有值相同的节点
思路:
1.后续遍历的最后一个节点就是树的根节点
2.在中序遍历中该根节点左边的是这棵树的左子树设长度为lnums,右边的是右子树个数为rnums
3.另外要知道后序遍历去掉根节点后,从左向右数,左边lnums个元素及树的左子树的后序遍历,之后rnums个元素即是右子树的后序遍历
从而可以获得新树的中序遍历和后序遍历,递归即可
public TreeNode buildTree(int[] inorder, int[] postorder) {
if(inorder.length == 0) return null;
return buildTree(inorder,0,inorder.length - 1, postorder, 0, postorder.length - 1);
}
public TreeNode buildTree(int[] inorder,int begin1,int end1, int[] postorder, int begin2,int end2){
if(end1 < begin1) return null;
int val = postorder[end2];
end2 --;
TreeNode node = new TreeNode(val);
//找到当前值在inorder中的位置
for (int i = begin1; i <= end1 ; i++) {
if (inorder[i] == val) {
node.left = buildTree(inorder, begin1, i - 1, postorder, begin2, begin2 + (i - 1 - begin1));
node.right = buildTree(inorder,i+1,end1,postorder,end2 - (end1 - i - 1),end2);
break;
}
}
return node;
}