题解 | #二叉排序树#

二叉排序树

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

插入过程:插入子树,返回根结点,若子树为空,则新建节点并做为根结点返回

#include <iostream>
using namespace std;
struct treeNode {
    int data;
    treeNode* leftChild;
    treeNode* rightChild;
    treeNode(int i) {
        data = i;
        leftChild = NULL;
        rightChild = NULL;
    }
};
treeNode* insert(treeNode* root, int x, int father) {
    if (root == NULL) {
        root = new treeNode(x);
        cout << father << endl;
    } else if (x >= root->data) {
        root->rightChild = insert(root->rightChild, x, root->data);
    } else {
        root->leftChild = insert(root->leftChild, x, root->data);
    }
    return root;
}
int main() {
    int n;
    while (cin >> n) { // 注意 while 处理多个 case
        // cout << a + b << endl;
treeNode* root = NULL;
        for (int i = 0; i < n; i++) {
            int temp;
            cin >> temp;
            root = insert(root, temp, -1);
        }

    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

11-08 10:39
门头沟学院 C++
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务