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;  
}  
相关推荐
Sakinol#1 分钟前
Leetcode Hot 100 ——回溯part01
算法·leetcode
feng_you_ying_li6 分钟前
list的介绍与底层实现
数据结构·c++·list
罗湖老棍子8 分钟前
【例 3】校门外的树(信息学奥赛一本通- P1537)
数据结构·算法·树状数组
guguhaohao19 分钟前
平衡二叉树(AVL),咕咕咕!
数据结构·c++·算法
一叶落43822 分钟前
LeetCode 137. 只出现一次的数字 II —— 位运算解法
c语言·数据结构·算法·leetcode·哈希算法
阿豪只会阿巴25 分钟前
咱这后续安排
c++·人工智能·算法·leetcode·ros2
像素猎人26 分钟前
以数据结构之——树来体会深度优先搜索【dfs】和广度优先搜索【bfs】的妙用:学比特算法课的自用笔记
数据结构·c++·学习·dfs·bfs·深度优先搜索
逆境不可逃31 分钟前
LeetCode 热题 100 之 215. 数组中的第K个最大元素 347. 前 K 个高频元素 295. 数据流的中位数
算法·leetcode·职场和发展
凤年徐35 分钟前
优选算法——滑动窗口
c++·算法
DDzqss39 分钟前
3.14打卡day35
算法