二叉搜索树的插入操作

在这里插入图片描述

class Solution {
public:
    TreeNode* insertIntoBST(TreeNode* root, int val) {
        if (root == nullptr) {     //中
            TreeNode* node = new TreeNode(val);
            return node;
        }
        if (val > root->val) {      //右
            root->right = insertIntoBST(root->right, val);  
        }
        if (val < root->val) {       //左
            root->left = insertIntoBST(root->left, val);
        }
        return root;
    }
};

时间复杂度:O(h) h为树的高度

思路:因为是二叉搜索树,递归可以有方向。如何递归,首先确定递归的返回值,明显是树的根节点,然后确定递归的终止条件,很明显当遍历到空节点是终止递归,终止的同时,返回插入的节点值,最终确定单层的递归逻辑,因为底层返回的插入的值,上一层就要接住底层返回的值,所以用到left和right来接住底层的返回值,最终返回root即可。

迭代法:

class Solution {
public:
    TreeNode* insertIntoBST(TreeNode* root, int val) {
        TreeNode* node = new TreeNode(val);
        if (root == nullptr) {
            return node;
        }
        TreeNode* cur = root;
        TreeNode* pre = root;    //找到前一个节点,方便插入
        while (cur != nullptr) {    //找到要插入的节点
            pre = cur;
            if (cur->val > val) {
                cur = cur->left;
            } else {
                cur = cur->right;
            }
        }
        if (val > pre->val) {   //判断查到节点左边还是右边
            pre->right = node;
        } else {
            pre->left = node;
        }
        return root;
    }
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值