题解 | #二叉排序树#

二叉排序树

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;
}

全部评论

相关推荐

哈哈哈哈哈哈哈哈哈哈这个世界太美好了
凉风落木楚山秋:毕业出路老师不管,你盖个章他好交差就完事了,等你盖完毕业了就不关他事情了
点赞 评论 收藏
分享
06-15 20:57
已编辑
门头沟学院 Java
CARLJOSEPH...:年轻人有傲气很正常,但是建议工作前洗净傲气。 说实在的,什么奖学金什么奖项的都很一般。尊重你的老师,在有时间的时候去上课,真遇到走不开的事,请态度端正地向你的老师说明情况,请求请假。我相信任何一个有师德的老师都会允许的(我的老师就是这样)。
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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