701. 二叉搜索树中的插入操作

发布时间 2023-04-11 17:52:34作者: xiazichengxi

给定二叉搜索树(BST)的根节点 root 和要插入树中的值 value ,将值插入二叉搜索树。 返回插入后二叉搜索树的根节点。 输入数据 保证 ,新值和原始二叉搜索树中的任意节点值都不同。

注意,可能存在多种有效的插入方式,只要树在插入后仍保持为二叉搜索树即可。 你可以返回 任意有效的结果 。

class Solution {
public:
//迭代法
    TreeNode* insertIntoBST(TreeNode* root, int val) {
        if(root == nullptr) return new TreeNode(val);
        TreeNode *cur = root;
        while(cur){
            if(cur->val > val) {
                pre = cur;
                cur = cur->left;
                if(cur == nullptr)
                {
                    cur = new TreeNode(val);
                    pre->left = cur;
                    return root;
                }
                continue;
            }
            if(cur->val < val) {
                pre = cur;
                cur = cur->right; 
                if(cur == nullptr)
                {
                    cur = new TreeNode(val);
                    pre->right = cur;
                    return root;
                }
                continue;
            }
        }
        return root;
    }
//递归
    TreeNode* insertIntoBST(TreeNode* root, int val){
        if(root == nullptr) return new TreeNode(val);
        if(val < root->val){
            TreeNode *left = insertIntoBST(root->left,val);
            root->left = left;
        }
        if(val > root->val){
            TreeNode *right = insertIntoBST(root->right,val);
            root->right = right;
        }
        return root;
    }
private:
    TreeNode *pre = nullptr;
};