# 剑指offer 4：重建二叉树

1 2 4 7 3 5 6 8

=》

=》

=》

=》

左子树
1
2
4
7

/**
* 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* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
int len=pre.size();
if(len==0)
return NULL;
vector<int>pre_left,pre_right,vin_left,vin_right;
int p_v=0;
for(int i=0;i<len;++i)
if(vin[i]==pre[0])
{
p_v=i;
break;
}
for(int i=0;i<p_v;++i)
{
pre_left.push_back(pre[i+1]);
vin_left.push_back(vin[i]);
}
for(int i=p_v+1;i<len;++i)
{
pre_right.push_back(pre[i]);
vin_right.push_back(vin[i]);
}
}
};

python

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
# 返回构造的TreeNode根节点
def reConstructBinaryTree(self, pre, tin):
if len(pre)==0:
return None
p_t=tin.index(pre[0])
pre_left=pre[1:p_t+1]
pre_right=pre[p_t+1:]
tin_left=tin[:p_t]
tin_right=tin[p_t+1:]
# write code here

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120