题目描述
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
解题思路
- 左子树的中序遍历数组长度为pos-1,元素为inorder[0]~inorder[pos-1];
- 左子树的后序遍历数组长度为pos-1,元素为postorder[0]~postorder[pos-1];
- 右子树的中序遍历数组长度为inorder.length-1-pos,元素为inorder[pos+1]~inorder[inorder.length-1];
- 右子树的中序遍历数组长度为inorder.length-1-pos,元素为postorder[pos]~postorder[postorder.length-2]。
代码
public TreeNode buildTree(int[] inorder, int[] postorder) {
TreeNode root;
int pos = 0;
if(inorder==null || postorder==null){
return null;
}
if(inorder.length==0|| postorder.length==0){
return null;
}
root = new TreeNode(postorder[postorder.length - 1]);
for(int i = 0;i < inorder.length;i++){
if(inorder[i]==postorder[postorder.length - 1]){
pos = i;
break;
}
}
int[] inorderLeftChild = Arrays.copyOfRange(inorder, 0, pos);
int[] postorderLeftChild = Arrays.copyOfRange(postorder, 0, pos);
int[] inorderRightChild = Arrays.copyOfRange(inorder, pos+1, inorder.length);
int[] postorderRightChild = Arrays.copyOfRange(postorder, pos, postorder.length-1);
TreeNode leftChild = buildTree(inorderLeftChild,postorderLeftChild);
TreeNode rightChild = buildTree(inorderRightChild,postorderRightChild);
root.left = leftChild;
root.right = rightChild;
return root;
}
1万+




被折叠的 条评论
为什么被折叠?



