题解 | #二叉排序树#

二叉排序树

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

#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,int &ans) {
    if (root == NULL) {
        root = (Tree)malloc(sizeof(TreeNode));
        root->left = NULL;
        root->right = NULL;
        root->num = num;
        ans = -1;
        return;
    }
    else if(root != NULL){
        int tag = 0;
        if (num < root->num) {
            if (root->left == NULL)
                tag = 1;
            Insert(root->left, num,ans);
            if (tag){
                 ans = root->num;
                return;
            }
        }
        else {
            if (root->right == NULL)
                tag = 1;
            Insert(root->right, num,ans);
            if (tag){
                ans = root->num;
                return;
            }
        }
    }
}
int main()
{
    int n, num,ans;
    while (cin >> n ) {
        Tree root = NULL;
        for (int i = 0; i < n; ++i) {
            cin >> num;
            Insert(root, num,ans);
            cout << ans << 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; void build(Tree &root,int val,int &parent){ if(root == NULL){ root = new TreeNode(val); return; } parent = root->val; if(val < root->val) build(root->left,val,parent); else build(root->right,val,parent); } 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; build(root,val,parent); cout << ( parent == val ? -1 : parent )<< endl; } } }</iostream>
点赞 回复 分享
发布于 2022-03-26 19:11

相关推荐

不愿透露姓名的神秘牛友
06-24 20:25
腾讯今年实习招了这么多人,后面秋招还会招人吗??想着秋招再战来着
牛客965593684号:腾讯好像2020年之后就是实习生招得多,应届生基本上不招,纯实习转正
点赞 评论 收藏
分享
06-15 18:44
黄淮学院 Java
Lynn012:如果是居民楼还是算了吧,看着有点野呢
点赞 评论 收藏
分享
程序员小白条:你是沟通了900个,不是投了900份简历,你能投900份,意味着对面都要回复你900次,你早就找到实习了,没亮点就是这样的,别局限地区,时间投的也要早,现在都要7月了
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

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