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;  
}  
相关推荐
贾斯汀玛尔斯几秒前
每天学一个算法--回溯算法(Backtracking)
算法
cpp_250110 分钟前
P2871 [USACO07DEC] Charm Bracelet S
数据结构·c++·算法·动态规划·题解·洛谷·背包dp
CoderCodingNo21 分钟前
【CSP】CSP-J 2019 江西真题 | 面积 luogu-P5681 (适合GESP一级、二级考生练习)
算法
Mr_pyx37 分钟前
【LeetHOT100】合并两个有序链表——Java多解法详解
算法
yu85939581 小时前
利用MATLAB进行木材图像去噪
开发语言·算法·matlab
cpp_25011 小时前
P2722 [USACO3.1] 总分 Score Inflation
数据结构·c++·算法·动态规划·题解·洛谷·背包dp
民乐团扒谱机1 小时前
【源码剖析】MATLAB混响函数底层逻辑拆解:Dattorro算法从公式到音频帧的完整推导
算法
淡海水1 小时前
【AI模型】概念-Token
人工智能·算法
凯瑟琳.奥古斯特1 小时前
数据结构核心知识点精要
数据结构·算法·排序算法
隔壁大炮1 小时前
Day02-04.张量点乘和矩阵乘法
人工智能·pytorch·深度学习·线性代数·算法·矩阵