代码随想录:二叉搜索时的插入

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
 * right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* insertIntoBST(TreeNode* root, int val) {
        TreeNode* ins = new TreeNode(val);
        if (root == NULL)
            return ins;
        if (root->val != val) {
            if (root->val < val) {
                if (root->right != NULL) {
                    insertIntoBST(root->right, val);
                } else {
                    root->right = ins;
                }
            }
            if (root->val > val) {
                if (root->left != NULL) {
                    insertIntoBST(root->left, val);
                } else {
                    root->left = ins;
                }
            }
        }
        return root;
    }
};
posted @ 2025-01-19 22:47  huigugu  阅读(6)  评论(0)    收藏  举报