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

https://leetcode.cn/problems/insert-into-a-binary-search-tree/

推荐使用没有返回值的方法,因为比较好想233

递归法:

class Solution {
public:
    TreeNode* pre=nullptr;
    TreeNode* insertIntoBST(TreeNode* root, int val) {
        TreeNode* backup = root;
        if(root==nullptr)return new TreeNode(val);
        dfs(root,val);
        return backup;
    }

    void dfs(TreeNode* root,int val)
    {  
        if(root==nullptr)
        {
            if(pre->val > val)pre->left=new TreeNode(val);
            else pre->right=new TreeNode(val);
            return;  
        }
        pre=root;
        if(root->val > val)dfs(root->left,val);
        else dfs(root->right,val);
    }
};


class Solution {
public:
    // 单层逻辑:判断能否插入到root的左节点或者右节点,能就进行插入返回root,不能就进入下一层
    TreeNode* insertIntoBST(TreeNode* root, int val) {
        // 找到空节点位置,此时是正确位置,可以插入
        if(!root)return new TreeNode(val);
        // 遍历左右子树,进行插入节点
        if(root->val > val)root->left = insertIntoBST(root->left,val);
        if(root->val < val)root->right = insertIntoBST(root->right,val);
        // 返回上一次递归处
        return root;
    }
};

 

迭代法:

class Solution {
public:

    TreeNode* insertIntoBST(TreeNode* root, int val) {
        TreeNode* backup = root;
        if(root==nullptr)return new TreeNode(val);
        TreeNode* pre=nullptr;
        while(root!=nullptr)
        {
            pre=root;
            if(root->val > val)root=root->left;
            else root=root->right;
        }
        if(pre->val > val){
            pre->left = new TreeNode(val);
        }else pre->right = new TreeNode(val);
        return backup;
    }
};

 

posted @ 2024-05-10 11:14  风乐  阅读(3)  评论(0编辑  收藏  举报