题解 | #二叉排序树#

二叉排序树

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

#include<iostream>
using namespace std;
int arr[101];
typedef struct BSTNode {
    int data;
    struct BSTNode* left;
    struct BSTNode* right;
}BSTNode, * BSTree;
void Insert_BST(BSTree& t, int k) {
    if (t == NULL) {
        t = (BSTNode*)malloc(sizeof(BSTNode));
        t->data = k;
        t->left = t->right = NULL;
        return;//return不是直接结束的好像,递归结束有问题
    }
    else if (t->data > k) {
        Insert_BST(t->left, k);
    }
    else {
        Insert_BST(t->right, k);
    }

}
void findPar(BSTree t, int k, int &p)//注意father是引用的
{
    
    /*if (t->data == k) {
        return;
    }
    else if (t->data > k) {
        findPar(t->left, k, p);
        p = t->data;

    }
    else {
        findPar(t->right, k, p);
        p = t->data;
    }这里递归我忘记了递归是从底层开始逐层往上返回的,所以最后这样写最后的father都是2
    */
    //用非递归方式,而且找路径而已非递归即可
    while (t->data != k) {
        p = t->data;
        if (t->data > k) {
            t = t->left;
        }
        else {
            t = t->right;
        }
    }




}
int main() {
    int N;
    while (cin >> N && N) {
        for (int i = 0; i < N; i++) {
            cin >> arr[i];
        }
        BSTree T = NULL;//初始化
        Insert_BST(T, arr[0]);
        cout << -1 << endl;
        for (int i = 1; i < N; i++) {
            Insert_BST(T, arr[i]);
            int father=0;//注意初始化
            findPar(T, arr[i], father);
            cout << father << endl;
        }



    }


}

全部评论

相关推荐

代码飞升:别用口语,后端就写后端,前端就写前端,最后别光后悔
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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