华中科技大学机试 二叉排序树 Easy *二叉树的构建方式

基本思想:

注意建树的引用问题;

要么return node*

要么node* &root

关键点:

无;

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<map>
#include<set>
using namespace std;

int n;

struct node {
    int data;
    node* left = NULL;
    node* right = NULL;
};

void insert(node* &root, int x,int& pre) {
    if (root == NULL) {
        root = new node;
        root->data = x;
        return;
    }
    pre = root->data;
    if (x > root->data) {
        insert(root->right, x, pre);
    }
    else {
        insert(root->left, x, pre);
    }
}

int main() {
    while (cin >>n) {
        int a;
        node* root = NULL;
        for (int i = 0; i < n; i++) {
            cin >> a;
            int pre = -1;
            insert(root, a, pre);
            cout << pre << endl;
        }
        //cout << 11 << endl;
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/songlinxuan/p/12417070.html