# 剑指offer--重建二叉树

Java代码：

/**
* Definition for binary tree
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
*/
public class Solution {
public TreeNode reConstructBinaryTree(int prestart ,int preend,int [] pre,int instart,int inend, int [] in){
TreeNode tree = new TreeNode(pre[prestart]);
tree.left = null;
tree.right = null;
if ( prestart == preend && instart == inend){
return tree;
}

int root = 0;
for (root = instart ; root < inend ; root++){
if ( pre[prestart] == in[root]){
break;
}
}

int leftlength = root - instart;
int rightlength = inend - root;
if ( leftlength > 0){
tree.left = reConstructBinaryTree(prestart+1, prestart+leftlength , pre, instart, root-1, in);
}
if ( rightlength > 0){
tree.right = reConstructBinaryTree(prestart+1+leftlength, preend, pre, root+1, inend, in);
}

return tree;
}

public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
if ( pre == null || in == null){
return null;
}
TreeNode root = reConstructBinaryTree(0, pre.length-1, pre, 0, in.length-1, in);
return root;
}
}

c++代码如下：

/**
* Definition for binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/

class Solution {
public:
TreeNode* Build(int* Pre,int* Vin ,int len){
if(!Pre || !Vin || len < 0){
return NULL;
}
int root_index = 0;
for(root_index = 0 ; root_index < len ; root_index++){
if(Vin[root_index] == Pre[0]){
break;
}
}
if(root_index == len){
return NULL;
}
TreeNode *root;
root = new TreeNode(Pre[0]);
root->left = root->right = NULL;
if(root_index > 0){
root->left = Build(Pre+1,Vin,root_index);
}
if(len-root_index-1 > 0){
root->right = Build(Pre+root_index+1,Vin+root_index+1,len-root_index-1);
}
return root;
}

TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
int len = pre.size();
int *Pre,*Vin;
Pre = new int[len];
Vin = new int[len];
for(int i = 0 ; i < len ; i++){
Pre[i] = pre[i];
Vin[i] = vin[i];
}
TreeNode *root = this->Build(Pre,Vin,len);
return root;
}
};

#### 剑指Offer:面试题6重建二叉树

2016-08-17 14:18:42

#### 剑指Offer——重建二叉树——C++

2016-11-25 10:52:45

#### 剑指offer——字符串的排列

2016-03-21 21:11:39

#### 剑指offer-重建二叉树-php

2017-04-04 16:43:38

#### 剑指Offer--重建二叉树

2017-07-01 16:40:14

#### 剑指offer-----重建二叉树(java版)

2017-01-10 08:46:20

#### 剑指offer--<重建二叉树>

2017-03-19 15:46:14

#### 【剑指Offer】重建二叉树

2015-09-16 14:01:40

#### 剑指offer--（4） 重建二叉树

2017-09-16 12:56:02

#### 剑指Offer面试题6（Java版）：重建二叉树

2015-07-27 18:36:52