二叉树根据先序,中序创建二叉树,后序,中序创建二叉树,层次序列,中序遍历创建二叉树。

本文介绍了如何通过先序、后序和层次序列配合中序序列来创建确定的二叉树。重点在于理解这些遍历方式如何确定根节点及左右子树的位置。文中提供了相关代码实现,并展示了程序运行的截图。
摘要由CSDN通过智能技术生成

在二叉树的创建过程中,先序,后序,层次序列这三种可以确定根的位置,只有中序序列可以确定左右子树的位置。所以我们可以通过(先序,中序),(后序,中序),(层次序列,中序)这三种情况创建一颗确定的二叉树。相关代码如下。

#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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值