题解 | 二叉排序树

二叉排序树

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

#include <bits/stdc++.h>
using namespace std;

struct TreeNode{
    int data;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int c):data(c),left(nullptr),right(nullptr){};
};
void InsertBST(TreeNode* &root,int c){
    if(root==nullptr){
        root=new TreeNode(c);
        return;
    }
    else if(c<root->data){
        InsertBST(root->left, c);
    }
    else if(c>root->data){
        InsertBST(root->right, c);
    }
    else if(c==root->data) return;
}
void PreOrder(TreeNode *root){
    if(root==nullptr) return;
    cout<<root->data<<" ";
    PreOrder(root->left);
    PreOrder(root->right);
}
void InOrder(TreeNode *root){
    if(root==nullptr) return;
    InOrder(root->left);
    cout<<root->data<<" ";
    InOrder(root->right);
}
void PostOrder(TreeNode *root){
    if(root==nullptr) return;
    PostOrder(root->left);
    PostOrder(root->right);
    cout<<root->data<<" ";
}
int main() {
    int n;
    while(cin>>n){
        TreeNode* root=nullptr;
        while(n>0){
            int a;
            cin>>a;
            InsertBST(root, a);
            n--;
        }
    PreOrder(root);
    cout<<endl;
    InOrder(root);
    cout<<endl;
    PostOrder(root);
    cout<<endl;
    }
    
    return 0;
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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