题目
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
分析
思路:
先来分析一下前序遍历和中序遍历得到的结果,
前序遍历第一位是根节点;
中序遍历中,根节点左边的是根节点的左子树,右边是根节点的右子树。
例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6}。
首先,根节点 是{ 1 };
左子树是:前序{ 2,4,7 } ,中序{ 4,7,2 };
右子树是:前序{ 3,5,6,8 } ,中序{ 5,3,8,6 };
这时,如果我们把左子树和右子树分别作为新的二叉树,则可以求出其根节点,左子树和右子树。
利用上述递归方式就可以实现重建二叉树。
github链接如下:JZ04-重建二叉树
C++代码
#include <iostream>
using namespace std;
#include <vector>
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 size = pre.size();
int *Pre,*Vin;
Pre = new int[size];
Vin = new int[size];
for(int i = 0 ; i < size ; i++){
Pre[i] = pre[i];
Vin[i] = vin[i];
}
TreeNode* root = this->Build(Pre,Vin,size);
return root;
}
TreeNode* Build(int* Pre,int* Vin,int size){
if(!Pre || !Vin || size < 0){
return NULL;
}
int root_index = 0;
for(root_index = 0 ; root_index < size ; root_index++){
if(Pre[0] == Vin[root_index]){
break;
}
}
if(root_index == size){
return NULL;
}
TreeNode* root;
root = new TreeNode(Pre[0]);
if(root_index > 0){
root->left = this->Build(Pre+1,Vin,root_index);
}
if(size - root_index - 1> 0){
root->right = this->Build(Pre+root_index+1,Vin+root_index+1,size-root_index-1);
}
return root;
}
};