# 【C++】根据二叉树的前序遍历和中序遍历构建一棵完整的树

#include <iostream>
#include <vector>
using namespace std;
struct Node{//****************************************************二叉树的节点
int ele;
Node *left;
Node *right;
Node(int n = 0){
ele = n;
left = NULL;
right = NULL;
}
};
Node* plantTree(vector<int> pre,vector<int> in)
{
if(pre.size()==0||in.size()==0||pre.size()!=in.size())//******递归基和错误条件
return NULL;

Node* root = new Node(pre[0]);//******************************创建根节点
int index = 0;
vector<int> left_pre,right_pre,left_in,right_in;//***********下面的递归需要的参数

for(int i = 0;i<in.size();i++)//*****************************在中序遍历里面找到根节点
if(root->ele==in[i])
index = i;

for(int i = 0;i<index;i++)
{
left_pre.push_back(pre[i+1]);//*************************根节点左子树前序遍历序列
left_in.push_back(in[i]);//*****************************根节点右左子树中序遍历序列
}

for(int j = index+1;j<pre.size();j++)
{
right_pre.push_back(pre[j]);//**************************根节点右子树前序遍历序列
right_in.push_back(in[j]);//****************************根节点右子树中序遍历序列
}

root->left = plantTree(left_pre,left_in);//*****************递归构建左子树
root->right = plantTree(right_pre,right_in);//**************递归构建右子树
return root;

}
void inorder(Node *root)//**************************************中序遍历
{
if(root==NULL)return;
inorder(root->left);
cout<<root->ele<<" ";
inorder(root->right);
}
int main()
{
Node *root = new Node(0);//**********************************构建一棵树
root->left = new Node(1);
root->right = new Node(2);
root->left->left = new Node(3);
root->left->right = new Node(4);
root->right->left = new Node(5);
root->right->right = new Node(6);

vector<int> pre,in;

pre.push_back(0);//*****************************************这棵树的前序遍历
pre.push_back(1);
pre.push_back(3);
pre.push_back(4);
pre.push_back(2);
pre.push_back(5);
pre.push_back(6);

in.push_back(3);//*******************************************这棵树的中序遍历
in.push_back(1);
in.push_back(4);
in.push_back(0);
in.push_back(5);
in.push_back(2);
in.push_back(6);

Node *newroot = plantTree(pre,in);//**************************通过前序遍历和中序遍历构建一棵树

cout<<"old tree inorder:";//**********************************中序遍历输出旧树和新树，验证结果
inorder(root);
cout<<endl;

cout<<"new tree inorder:";
inorder(newroot);
cout<<endl;

return 0;
}

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

120