二叉树的建立和遍历

已知二叉树的完全前序序列可以唯一确定一棵二叉树。现给出二叉树的完全前序序列,使用C或C++编写算法完成:
(1) 以二叉链表为存储结构,建立二叉树;
(2) 编写先序遍历算法,输出先序遍历序列;
(3) 编写中序遍历算法,输出中序遍历序列;
(4) 编写后序遍历算法,输出后序遍历序列;
(5) 编写层序遍历算法,输出层序遍历序列,要求按层输出,每层输出一行;
(6) 编写算法,计算并输出二叉树的叶子数;
(7) 编写算法,计算并输出二叉树的高度。

输入格式:

二叉树数据元素为单个字符且各不相同,取值范围为A~Z,a~z,二叉树不为空。输入数据分为2行,第1行为二叉树完全前序序列字符(包括#)个数,第2行为二叉树的完全前序序列。例如,上面二叉树的输入为:ABD##FE###CG#H##I##,其中#代表为空的位置。

#include <iostream>
#include <bits/stdc++.h>
using namespace std;

typedef char telem;
int n,i;
char a[100];
int cnt=0;
typedef struct BTNode
{
    telem data;
    struct BTNode *left;
    struct BTNode *right;

} Node;

Node* createBT()
{
    Node *p;
    telem ch;
    ch=a[cnt];
    if(ch=='#')
    {
        p=NULL;
        cnt++;
    }
    else
    {
        cnt++;
        p=(Node*)malloc(sizeof(Node));
        p->data = ch;
        p->left = createBT();
        p->right = createBT();

    }

    return p;
}

void xianxu(Node* root)
{
    if(root)
    {
        cout<< root->data;
        xianxu(root->left);
        xianxu(root->right);
    }
}

void zhongxu(Node* root)
{
    if(root)
    {
        zhongxu(root->left);
        cout << root->data;
        zhongxu(root->right);
    }
}

void houxu(Node* root)
{
    if(root)
    {
        houxu(root->left);
        houxu(root->right);
        cout << root->data;
    }
}

int yezijiedianshu(Node* root)
{
    if(!root)
    {
        return 0;
    }
    else if((root->left == NULL)&&(root->right == NULL))
    {
        return 1;
    }
    else
    {
        return yezijiedianshu(root->left)+yezijiedianshu(root->right);
    }
}

int gaodu(Node* root)
{
    if(root)
    {
        return gaodu(root->left)>gaodu(root->right)?gaodu(root->left)+1:gaodu(root->right)+1;
    }
    if(root == NULL)
    {
        return 0;
    }
}
int main()
{
    cin >>n;
    for(i=0; i<n; i++)
    {
        cin >>a[i];
    }
    Node *root=NULL;
    root = createBT();
    cout <<"preorder traversal:";
    xianxu(root);
    cout <<endl;
    cout <<"inorder traversal:";
    zhongxu(root);
    cout <<endl;
    cout <<"postorder traversal:";
    houxu(root);
    cout <<endl;
    cout <<yezijiedianshu(root)<<endl;
    cout <<gaodu(root)<<endl;
    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值