排序二叉树

题目信息

排序二叉树是指左子树的所有节点的值均小于它根节点的值,右子树的所有节点的值均大于它根节点的值。

输入

输入有一行,表示若干个要排序的数,输入0时停止

输出

二叉树的凹入表示
和二叉树的中序遍历序列

测试样例

42 168 35 101 270 125 79 259 263 165 6 246 182 62 192 296 243 28 37 0 
        6
            28
    35
        37
42
                62
            79
        101
            125
                165
    168
                    182
                        192
                            243
                246
            259
                263
        270
            296

 6 28 35 37 42 62 79 101 125 165 168 182 192 243 246 259 263 270 296

测试样例2

147 106 291 130 71 51 7 202 94 249 132 24 85 0 
                7
                    24
            51
        71
                85
            94
    106
        130
            132
147
        202
            249
    291

 7 24 51 71 85 94 106 130 132 147 202 249 291

解答

#include<iostream>

using namespace std;

typedef struct NODE
{
    int data; //数据域
    NODE *Left; //左孩子
    NODE *Right; //右孩子
} BSnode, *BSTree;

bool Insert(BSTree *root, int e)
{
    if ((*root) == NULL)
    {//该树为一棵空树,创建一个新节点作为根节点
        (*root) = new BSnode;
        (*root)->data = e;
        (*root)->Left = NULL;
        (*root)->Right = NULL;
        return true;
    }
    else if (e == (*root)->data)
    {//数值相同,则不再继续插入
        return false;
    }
    else if (e < (*root)->data)
    {
        Insert(&(*root)->Left, e);
    }
    else
    {
        Insert(&(*root)->Right, e);
    }
}

void printBIT(BSTree root, int x)
{
    if (root != NULL)
    {
        printBIT(root->Left, x + 1);
        for (int i = 0; i < x; i++)
            cout << "    ";
        cout << root->data << endl;
        printBIT(root->Right, x + 1);
    }
}

void inorder(BSTree root)
{//二叉树的中序遍历
    if (root != NULL)
    {
        inorder(root->Left);
        cout << " " << root->data;
        inorder(root->Right);
    }
}

int main()
{
    //freopen("/Users/zhj/Downloads/test.txt", "r", stdin);
    BSTree root = NULL;
    int x;
    while (1)
    {
        cin >> x;
        if (x == 0)
        {
            break;
        }
        else
        {
            Insert(&root, x);
        }
    }
    printBIT(root, 0);
    cout << endl;
    inorder(root);
    cout << endl;
    return 0;
}

本题中注意的是按照输入顺序来安排排序二叉树的,既假定第一个输入的数即为根节点

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhj12399

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值