题解java| #重建二叉树#
重建二叉树
http://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
通过分割数组 递归实现,前序 1 2473568 中序 472 1 5386 这样就获得第一个节点1,然后1的左子树前序 247与中序 472再递归成 2 47 ,47 2 一直分隔到只有一个节点
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] vin) {
return fenge(pre,vin,0,pre.length-1,0, vin.length-1);
}
static public TreeNode fenge(int [] pre,int [] vin,int left,int right,int left1,int right1) {
if(pre.length==0){
return null;
}
TreeNode node=null;
if (left<=right &&left1<=right1 &&left<pre.length&&left1<vin.length) {
node = new TreeNode(pre[left]);
int count = 0;
while (vin[count+left1] != node.val) {
count++;
//
}
TreeNode leftNode = fenge(pre, vin, left + 1, count + left, left1, count + left1 - 1);
TreeNode rightNode = fenge(pre, vin, count + left + 1, right, count + left1 + 1, right1);
node.left=leftNode;
node.right=rightNode;
}
return node ;
// new TreeNode(pre[left])
}
}