#3730. [GESP202409 六级 C++] 第 12 题

[GESP202409 六级 C++] 第 12 题

二叉搜索树中的每个结点,其左子树的所有结点值都小于该结点值,右子树的所有结点值都大于该结点值。以下代码对给定的整数数组(假设数组中没有数值相等的元素),构造一个对应的二叉搜索树,横线上应填写( ):

// 定义二叉树的结点结构
struct tree_node {
    int val;
    tree_node* left;
    tree_node* right;

    tree_node(int x) : val(x), left(nullptr), right(nullptr) {}
};

// 插入结点到二叉搜索树中
tree_node* insert(tree_node* root, int val) {
    if (root == nullptr) {
        return new tree_node(val);
    }

    ________________ // 在此处填入代码

    return root;
}

// 根据给定数组构造二叉搜索树
tree_node* constructBST(const int arr[], int size) {
    tree_node* root = nullptr;

    for (int i = 0; i < size; ++i) {
        root = insert(root, arr[i]);
    }
    return root;
}

A.

if (val < root->val)
  root->left = insert(root->left, val);
else
  root->right = insert(root->right, val);

B.

if (val > root->val)
  root->left = insert(root->left, val);
else
  root->right = insert(root->right, val);

C.

if (val < root->val)
  root->left = insert(root, val);
else
  root->right = insert(root, val);

D.

if (val > root->val)
  root->left = insert(root, val);
else
  root->right = insert(root, val);

{{ select(1) }}

  • A
  • B
  • C
  • D