题解:基于递归 | #二叉树根节点到叶子节点的所有路径和#
重建二叉树
http://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6
import java.util.*;
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
int[] pre;
int[] vin;
int p;//记录pre中,已经被处理到的节点的索引
public TreeNode reConstructBinaryTree(int [] pre,int [] vin) {
this.pre = pre;
this.vin = vin;
p=0;
return reConstructBinaryTree(0,pre.length-1);
}
public TreeNode reConstructBinaryTree(int start,int end) {
for(int i=start;i<=end;i++){
if(vin[i]==pre[p]){
TreeNode node=new TreeNode(pre[p]);
p++;
node.left=reConstructBinaryTree(start,i-1);
node.right=reConstructBinaryTree(i+1,end);
return node;
}
}
return null;
}
}