[ 二叉树 ] 二叉搜索树中的插入操作

701. 二叉搜索树中的插入操作 - 力扣(LeetCode) (leetcode-cn.com)

二叉搜索树中的插入操作

递归

  • 多说一句: Leetcode提供的默认函数并不是确定的, 我们函数的返回值和参数需要我们自己思考。
  • 比如,我们要插入一个结点,我们要找到新结点,此处是null;我们要找到位置的父结点。
  • 此时我们在找到结点时返回父结点就很简单。所以我们要根据我们要干什么先确定参数和返回值
class Solution {
public:
    TreeNode* insertIntoBST(TreeNode* root, int val) {
        // 找到空位置, 构造新结点插入
        if (!root) {
            TreeNode* node = new TreeNode(val);
            return node;
        }
        if (root->val > val) root->left = insertIntoBST(root->left, val);
        if (root->val < val) root->right = insertIntoBST(root->right, val);
        return root;
    }
};

非递归

  • BST的操作通常非递归方法更好理解
class Solution {
public:
    TreeNode* insertIntoBST(TreeNode* root, int val) {
        // 构造插入节点
        TreeNode* node = new TreeNode(val);
        
        if (!root) return node;
        TreeNode* cur = root;
        TreeNode* parent = root;
        // 找到插入节点
        while (cur) {
            parent = cur;
            if (cur->val > val) cur = cur->left;
            else cur = cur->right;
        }
        // 判断插入的结点是左孩子还是右孩子
        if (val < parent->val) parent->left = node;
        else parent->right = node;
        return root;
    }
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值