在二叉树的创建过程中,先序,后序,层次序列这三种可以确定根的位置,只有中序序列可以确定左右子树的位置。所以我们可以通过(先序,中序),(后序,中序),(层次序列,中序)这三种情况创建一颗确定的二叉树。相关代码如下。
#include <iostream>
#include <queue>
#include <deque>
using namespace std;
typedef char ElementType;
struct Node
{
ElementType data;
Node* lchild;
Node* rchild;
};
//创建一个新节点
Node* newNode(ElementType v)
{
Node* node = new Node;
node->data = v;
node->lchild = NULL;
node->rchild = NULL;
return node;
}
//搜索值为x,并将其修改为newdata
void search_tree(Node* root, int x, int newdata)
{
if (root = NULL)
{
return;
}
if (root->data = x)
{
root->data = newdata;
}
search_tree(root->lchild, x, newdata);
search_tree(root->rchild, x, newdata);
}
//插入节点
void insert(Node* &root, int x)
{
if (root == NULL)
{
root = new Node;
root->data = x;
root->lchild = NULL;
root->rchild = NULL;
return;
}
if(x<root->data)
insert(root->lchild, x);
else
insert(root->rchild, x);
}
//创建
Node* create(int data[], int n)
{
Node* root=NULL;
for (int i = 0;i < n;i++)
{
insert(roo