[LeetCode] 701. Insert into a Binary Search Tree

本文详细介绍了如何在二叉搜索树(BST)中插入一个新值,保持其搜索树特性。通过递归方法,文章解释了根据值大小判断插入节点位置的过程,确保树的左子树所有值小于根节点,右子树所有值大于根节点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given the root node of a binary search tree (BST) and a value to be inserted into the tree, insert the value into the BST. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.

Note that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.

For example,

Given the tree:
        4
       / \
      2   7
     / \
    1   3
And the value to insert: 5

You can return this binary search tree:

         4
       /   \
      2     7
     / \   /
    1   3 5

This tree is also valid:

         5
       /   \
      2     7
     / \   
    1   3
         \
          4

Solution:

解决这个题目需要了解一下BST二叉搜索树的知识。BST是二叉树的一种形式,需要满足下面的几个条件。

1.满足二叉树,只有两个子结点

2.所有结点的值是唯一的

3.左结点的值小于父结点的值,右结点的值大于父结点的值

了解了BST的知识我们再来看如何对二叉树进行插入操作。因为二叉树的操作肯定是一个递归或者迭代的操作。所以对于任意的root结点进行插入操作,我们应该先比较插入值的大小跟root值的大小。如果大于root的值就插入到右边,反之插入到左边。下面给出用简单递归的方法实现:

class Solution {
    public TreeNode insertIntoBST(TreeNode root, int val) {
        TreeNode node=new TreeNode(val);
        if(root==null) return node;
        if(root.val>val){
              if(root.left==null){
            root.left=node;
              }else{
            root.left= insertIntoBST(root.left,val);
              }
        }
        else{
            if (root.right==null){
              root.right=node;}
            else{
                root.right=insertIntoBST(root.right,val);
            }
        }
        return root;
    }
    }

转载于:https://www.cnblogs.com/rever/p/10353272.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值