2. 排序二叉树

题目

建立并中序遍历一个排序二叉树

排序二叉树是指左子树的所有节点的值均小于它根节点的值,右子树的所有节点的值均大于它根节点的值,如下图是一棵排序二叉树

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

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

sample:
input:
56 78 34 89 12 35 67 77 22 57 0

output:
        12
            22
    34
        35
56
            57
        67
            77
    78
        89

12 22 34 35 56 57 67 77 78 89

C++代码

#include<iostream>  
using namespace std;  
  
struct node {  
    int val;  
    node* left;  
    node* right;  
};  
  
node* newNode(int key) {  
    node* Node = new node();  
    Node->val = key;  
    Node->left = NULL;  
    Node->right = NULL;  
    return(Node);  
}  
  
node* insertNode(node* root, int val) {  
    if (root == NULL) {  
        return newNode(val);  
    }  
    if (val < root->val) {  
        root->left = insertNode(root->left, val);  
    }  
    else if (val > root->val) {  
        root->right = insertNode(root->right, val);  
    }  
    return root;  
}  
  
void printInorder(node* root) {  
    if (root != NULL) {  
        printInorder(root->left);  
        cout << ' ';  
        cout << root->val;  
        printInorder(root->right);  
    }  
}  
  
void printTree(node* root, int space) {  
    if (root != NULL) {  
        printTree(root->left, space+4);  
        for (int i = 0; i < space; i++) cout << " ";  
        cout <<root->val << endl;  
        printTree(root->right, space+4);  
    }  
}  
  
int main() {  
    int num;  
    cin >> num;  
    node* root = NULL;  
    while (num != 0) {  
        root = insertNode(root, num);  
        cin >> num;  
    }  
    printTree(root,0);  
    cout << endl ;  
    printInorder(root);  
    cout << endl;  
    return 0;  
}  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

榆榆欸

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

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

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

打赏作者

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

抵扣说明:

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

余额充值