题解 | 二叉排序树

二叉排序树

https://www.nowcoder.com/practice/30a0153649304645935c949df7599602

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

struct TreeNode{
    int data;
    TreeNode *left;
    TreeNode *right;
    TreeNode *parent;
    TreeNode(int c,TreeNode* p = nullptr):data(c),left(nullptr),right(nullptr),parent(p){};
};

int Insert(TreeNode* &root,int c, TreeNode* p = nullptr){
    if(root==nullptr){
        root = new TreeNode(c,p);
        if(p==nullptr) return -1;
        else return p->data;
    }
    else if(c>root->data){
        return Insert(root->right,c,root);
    }
    else if(c<root->data){
        return Insert(root->left, c,root);
    }
    return -1;
}

int main() {
    int n;
    cin>>n;
    TreeNode* root = nullptr;
    while(n>0){
        int a;
        cin>>a;
        int parent = Insert(root,a);
        cout<<parent<<endl;
        n--;
    }
    return 0;
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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