此题与先序中序转后序类似(由先序去划分中序,主要是依据根节点--》还原树需中序),不同的是 创建节点。
创建节点时注意的地方是,字符长度》=1时需创建,0时返回。创建为先序的方式,if( *root == NULL)!
另注意,Node **root误写成Node *root 俩者的后果是,指针的操作并未保存。传进来的root仍为NULL!!
#include <iostream>
#include <string>
#include "vld.h"
using namespace std;
struct Node
{
Node *left;
Node *right;
char val;
Node(char ch)
{
left = NULL;
right = NULL;
val = ch;
}
};
void pre_order(Node *root);
void build_bin_tree(string pre,string inorder,Node **root);
void del_tree(Node *root);
int main()
{
string pre = "abcdefghi";//abdecg //abcdefghi
string inorder = "cbefdahgi";//dbeacg //cbefdahgi
Node *root = NULL; //注意初始化!
build_bin_tree(pre,inorder,&root);
cout<<"pre_order"<<endl;
pre_order(root);
del_tree(root);
root = NULL;
return 0;
}
void build_bin_tree(string pre,string inorder,Node **root)
{
if(pre.empty() || inorder.empty())return ; //可能没有节点!
if( *root == NULL)//根节点
{
*root = new Node(pre[0]);
}
if(pre.length() == 1)//的先建节点再返回!
{
return ;
}
int index = inorder.find(pre[0]);
//建左子树
build_bin_tree(pre.substr(1,index),inorder.substr(0,index),&((*root)->left));
//建右子树
build_bin_tree(pre.substr(index+1,pre.length()-index-1),inorder.substr(index+1,pre.length()-index-1),&((*root)->right));
}
void pre_order(Node *root)//先序
{
if (root == NULL) return;
cout<<root->val<<" ";
pre_order(root->left);
pre_order(root->right);
}
void del_tree(Node *root)
{
if (root == NULL) return;
del_tree(root->left);
del_tree(root->right);
delete(root);
}

本文介绍了一种通过先序遍历和中序遍历字符串构建二叉树的方法,并实现了相应的C++代码。文章详细解释了构建过程中的关键步骤,包括如何确定根节点以及如何递归地构建左右子树。

2692

被折叠的 条评论
为什么被折叠?



