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;  
}  
相关推荐
森焱森3 分钟前
无人机三轴稳定化控制(1)____飞机的稳定控制逻辑
c语言·单片机·算法·无人机
循环过三天7 分钟前
3-1 PID算法改进(积分部分)
笔记·stm32·单片机·学习·算法·pid
呆瑜nuage17 分钟前
数据结构——堆
数据结构
蓝澈112123 分钟前
弗洛伊德(Floyd)算法-各个顶点之间的最短路径问题
java·数据结构·动态规划
zl_dfq26 分钟前
数据结构 之 【堆】(堆的概念及结构、大根堆的实现、向上调整法、向下调整法)(C语言实现)
数据结构
127_127_12728 分钟前
2025 FJCPC 复建 VP
数据结构·图论·模拟·ad-hoc·分治·转化
闪电麦坤9532 分钟前
数据结构:二维数组(2D Arrays)
数据结构·算法
凌肖战44 分钟前
力扣网C语言编程题:快慢指针来解决 “寻找重复数”
c语言·算法·leetcode
埃菲尔铁塔_CV算法1 小时前
基于 TOF 图像高频信息恢复 RGB 图像的原理、应用与实现
人工智能·深度学习·数码相机·算法·目标检测·计算机视觉
NAGNIP2 小时前
一文搞懂FlashAttention怎么提升速度的?
人工智能·算法