题目
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode constructFromPrePost(int[] pre, int[] post) {
if (pre.length == 0 || post.length == 0) return null;
//数组长度为1时,直接返回即可
if(pre.length==1) {
return new TreeNode(pre[0]);
}
TreeNode root = new TreeNode(pre[0]);
for (int i = 0; i < pre.length; ++i){
if (post[i] == pre[1]){ //第二个根
int round = i+1; //后序遍历数组前半部分从0截到i+1,因为post[i]本身也是左子树的一个结点
int[] pre_left = Arrays.copyOfRange(pre, 1, round+1); //从1开始截,因为个数与post_left相同,所以要加1
int[] pre_right = Arrays.copyOfRange(pre, round+1, pre.length);
int[] post_left = Arrays.copyOfRange(post, 0, round); //从0截取到包括他本身post[i]
int[] post_right = Arrays.copyOfRange(post, round, post.length-1);
root.left = constructFromPrePost(pre_left, post_left); //将创建左子树所需的结点传入
root.right = constructFromPrePost(pre_right, post_right);
break;
}
}
return root;
}
}