题解 | #二叉排序树#

二叉排序树

http://www.nowcoder.com/practice/b42cfd38923c4b72bde19b795e78bcb3

#include<iostream>
using namespace std;
typedef struct node {
    int num;
    struct node* left, * right;
    node(int n) :num(n), left(NULL), right(NULL) {}
}TreeNode, * Tree;
void Insert(Tree& root, int num) {
    if (root == NULL) {
        root = (Tree)malloc(sizeof(TreeNode));
        root->left = NULL;
        root->right = NULL;
        root->num = num;
    }
    else
        if (num < root->num)
            Insert(root->left, num);
        else if(num > root->num)
            Insert(root->right, num);
}
void Output1(Tree root) {
    if (root == NULL)
        return;
    cout << root->num << " ";
    Output1(root->left);
    Output1(root->right);
}
void Output2(Tree root) {
    if (root == NULL)
        return;
    Output2(root->left);
    cout << root->num << " ";
    Output2(root->right);
}
void Output3(Tree root) {
    if (root == NULL)
        return;
    Output3(root->left);
    Output3(root->right);
    cout << root->num << " ";
}
int main()
{
    int n, num, ans;
    while (cin >> n) {
        Tree root = NULL;
        for (int i = 0; i < n; ++i) {
            cin >> num;
            Insert(root, num);
        }
        Output1(root);
        cout << endl;
        Output2(root);
        cout << endl;
        Output3(root);
        cout << endl;
    }
}
全部评论
#include<iostream> using namespace std; typedef struct node{ int val; struct node *left,*right; node(int v):val(v),left(NULL),right(NULL){} }TreeNode,*Tree; Tree build(Tree root,int val){ if(root == NULL) root = new TreeNode(val); else if(val < root->val) root->left = build(root->left,val); else if(val > root->val) root->right = build(root->right,val); return root; } void PreOrder(Tree root){ if(root != NULL){ cout << root->val << " "; PreOrder(root->left); PreOrder(root->right); } } void InOrder(Tree root){ if(root != NULL){ InOrder(root->left); cout << root->val << " "; InOrder(root->right); } } void PostOrder(Tree root){ if(root != NULL){ PostOrder(root->left); PostOrder(root->right); cout << root->val << " "; } } int main() { ios::sync_with_stdio(false); cin.tie(0); int n,val,parent; while(cin >> n){ Tree root = NULL; parent = -1; while(n--){ cin >> val; root = build(root,val); } PreOrder(root); cout << endl; InOrder(root); cout << endl; PostOrder(root); cout << endl; } }</iostream>
点赞 回复 分享
发布于 2022-03-26 19:23

相关推荐

秋国🐮🐴:拿到你简历编号然后让你知道世间险恶
点赞 评论 收藏
分享
02-17 01:46
门头沟学院 Java
咩咩子_:请填空,你是我见过______
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务