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;  
}  
相关推荐
张辰宇-16 分钟前
AcWing 5 多重背包问题 II
算法
小则又沐风a31 分钟前
类和对象(C++)---上
java·c++·算法
季明洵36 分钟前
动态规划及背包问题
java·数据结构·算法·动态规划·背包问题
busideyang42 分钟前
函数指针类型定义笔记
c语言·笔记·stm32·单片机·算法·嵌入式
Wect44 分钟前
LeetCode 215. 数组中的第K个最大元素:大根堆解法详解
前端·算法·typescript
深邃-1 小时前
数据结构-双向链表
c语言·开发语言·数据结构·c++·算法·链表·html5
2401_878530211 小时前
分布式任务调度系统
开发语言·c++·算法
_深海凉_1 小时前
LeetCode热题100-两数之和
算法·leetcode·职场和发展
nunca_te_rindas1 小时前
算法刷体小结汇总(C/C++)20260328
c语言·c++·算法
Sunshine for you1 小时前
高性能压缩库实现
开发语言·c++·算法