题解 | #二叉排序树#

二叉排序树

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

#include <iostream>
using namespace std;
int n;
struct Node{
    int val;
    Node *left, *right;
    Node(int _val):val(_val), left(NULL), right(NULL){}
};

void insert(Node* &root, int x){
    if(!root)  root = new Node(x);
    else if(x > root->val) insert(root->right, x);
    else if(x < root->val) insert(root->left, x);
    //else return;
}

void dfs(Node* root, int op){
    if(!root) return;
    if(op == 1) cout<<root->val<<' ';
    dfs(root->left, op);
    if(op == 2) cout<<root->val<<' ';
    dfs(root->right, op);
    if(op == 3) cout<<root->val<<' ';

}

int main(){
    Node *root;
    while(cin>>n){
        root = NULL;
        for(int i = 0; i < n; i ++){
            int x;
            cin>>x;
            insert(root, x);
        }
        for(int i = 1; i <= 3; i ++){
            dfs(root, i);
            cout<<endl;
        }
    }
    return 0;
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
昨天 14:35
点赞 评论 收藏
分享
白火同学:大二有这水平很牛了,可以适当对关键信息加粗一点,比如关键技术、性能指标之类的。
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务