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++代码

cpp 复制代码
#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;  
}  
相关推荐
我真不是小鱼18 分钟前
cpp刷题打卡记录27——无重复字符的最长子串 & 找到字符串中所有字母的异位词
数据结构·c++·算法·leetcode
XuecWu322 分钟前
原生多模态颠覆Scaling Law?解读语言“参数需求型”与视觉“数据需求型”核心差异
人工智能·深度学习·算法·计算机视觉·语言模型
We་ct23 分钟前
LeetCode 69. x 的平方根:两种解法详解
前端·javascript·算法·leetcode·typescript·平方
一直不明飞行25 分钟前
C++:string,写法s.find(‘@‘) != s.end()是否有问题
开发语言·c++·算法
Proxy_ZZ036 分钟前
打造自己的信道编码工具箱——Turbo、LDPC、极化码三合一
c语言·算法·信息与通信
wayz1138 分钟前
21天机器学习核心算法学习计划(量化方向)
学习·算法·机器学习
qq. 280403398439 分钟前
数据结构引论
前端·数据结构
穿条秋裤到处跑40 分钟前
每日一道leetcode(2026.04.09):区间乘法查询后的异或 II
算法·leetcode
超级大只老咪1 小时前
一维度前缀和解题通用模板(java)
java·开发语言·算法
weixin_513449961 小时前
walk_these_ways项目学习记录第十篇(通过行为多样性 (MoB) 实现地形泛化)--从仿真到部署
人工智能·学习·算法