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

这道题让我们在二叉搜索树中插入结点,当前还需要保持二叉搜索树的性质,那么插入结点的方式就有多种,就像题目中给的那个例子。结点5可以有不同的方法,但是很显然,放在结点7的左子结点比代替结点4成为根结点要来的简单许多。怎么简单我们就怎么来,所以还是按照简单的来吧。由于二叉搜索树自带二分的性质,那么首先根结点比较,如果大于根结点值的话,说明肯定要插入到右子树中。所以接下来跟7比较,对于递归函数来说,结点7也可以当作是一个新的根结点,那么由于结点7的值大于目标值5,所以要去其左子树,我们发现其左子结点为空,那么我们就可以根据目标值来生成一个新的结点,然后连到结点7的左子树上即可。那么在递归函数中,首先判断当前结点是否为空,为空的话就新建一个结点返回。否则就判断当前结点值是否大于目标值,是的话就对左子结点调用递归函数,并将返回值赋给当前结点的左子结点,否则就对右子结点调用递归函数,并将返回值赋给当前结点的右子结点,最后返回当前结点即可,参见代码如下:

解法一:

class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if (!root) return new TreeNode(val);
if (root->val > val) root->left = insertIntoBST(root->left, val);
else root->right = insertIntoBST(root->right, val);
return root;
}
};

我们也可以不使用递归来做,而是用迭代。整体思路跟递归并没有太大的区别,但没有递归写法简洁。首先还是判空,若为空,就新建结点返回。然后用一个变量cur来遍历,在while循环中,如果当前值大于目标值,如果其左子结点不存在,那么我们新建结点,并连上其左子结点,并跳出循环;若左子结点存在,则cur指向其左子结点。否则,当前值小于目标值,若其右子结点不存在,新建结点并连上其右子结点,并跳出循环;若右子结点存在,则cur指向其右子结点。最后返回root即可,参见代码如下:

解法二:

class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if (!root) return new TreeNode(val);
TreeNode *cur = root;
while (true) {
if (cur->val > val) {
if (!cur->left) {cur->left = new TreeNode(val); break;}
cur = cur->left;
} else {
if (!cur->right) {cur->right = new TreeNode(val); break;}
cur = cur->right;
}
}
return root;
}
};

类似题目:

Search in a Binary Search Tree

参考资料:

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

https://leetcode.com/problems/insert-into-a-binary-search-tree/discuss/150757/java-iterative-100

https://leetcode.com/problems/insert-into-a-binary-search-tree/discuss/164137/Java-easy-to-understand-solution

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Insert into a Binary Search Tree 二叉搜索树中插入结点的更多相关文章

  1. [LeetCode] Search in a Binary Search Tree 二叉搜索树中搜索

    Given the root node of a binary search tree (BST) and a value. You need to find the node in the BST ...

  2. Leetcode501.Find Mode in Binary Search Tree二叉搜索树中的众数

    给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素). 假定 BST 有如下定义: 结点左子树中所含结点的值小于等于当前结点的值 结点右子树中所含结点的值大于等于当 ...

  3. Leetcode700.Search in a Binary Search Tree二叉搜索树中的搜索

    给定二叉搜索树(BST)的根节点和一个值. 你需要在BST中找到节点值等于给定值的节点. 返回以该节点为根的子树. 如果节点不存在,则返回 NULL. class Solution { public: ...

  4. LeetCode701 二叉搜索树中插入结点

    给定二叉搜索树(BST)的根节点和要插入树中的值,将值插入二叉搜索树. 返回插入后二叉搜索树的根节点. 保证原始二叉搜索树中不存在新值. 注意,可能存在多种有效的插入方式,只要树在插入后仍保持为二叉搜 ...

  5. LeetCode Recover Binary Search Tree——二查搜索树中两个节点错误

    Two elements of a binary search tree (BST) are swapped by mistake.Recover the tree without changing ...

  6. [LeetCode] Delete Node in a BST 删除二叉搜索树中的节点

    Given a root node reference of a BST and a key, delete the node with the given key in the BST. Retur ...

  7. [LeetCode] Lowest Common Ancestor of a Binary Search Tree 二叉搜索树的最小共同父节点

    Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BS ...

  8. [LeetCode] 235. Lowest Common Ancestor of a Binary Search Tree 二叉搜索树的最小共同父节点

    Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BS ...

  9. [LeetCode] 235. Lowest Common Ancestor of a Binary Search Tree 二叉搜索树的最近公共祖先

    Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BS ...

随机推荐

  1. 中间件方法必须返回Response对象实例(tp5.1+小程序结合时候出的问题)

    前言:在最近开发小程序通过中间件检查是否携带token时候报的一个错误 解决方法: 根据手册中需要return出去才可以不报错

  2. 微星X470主板装机

    记录一下装机过程,以作纪念 配置 机箱:先马黑洞3 电源:先马金牌500w CPU:AMD 锐龙5:2600X 主板:微星 X470 暗黑版 显卡:七彩虹 RTX2060 内存:科赋 3200,2条8 ...

  3. 第十三节:实际开发中使用最多的监视锁Monitor、lock语法糖的扩展、混合锁的使用(ManualResetEvent、SemaphoreSlim、ReaderWriterLockSlim)

    一. 监视锁(Monitor和lock) 1. Monitor类,限定线程个数的一把锁,两个核心方法: Enter:锁住某个资源. Exit:退出某一个资源. 测试案例:开启5个线程同时对一个变量进行 ...

  4. 第四节: EF调用存储过程的通用写法和DBFirst模式子类调用的特有写法

    一. 背景 上一个章节,介绍了EF调用两类SQL语句,主要是借助 ExecuteSqlCommand  和 SqlQuery 两个方法来完成,在本章节主要是复习几类存储过程的写法和对应的EF调用这几类 ...

  5. 13、 使用openpyxl存储周杰伦的歌曲信息

      import requests import openpyxl res = requests.get('https://c.y.qq.com/soso/fcgi-bin/client_search ...

  6. redis 数据结构及应用场景

    1. String 常用命令: get.set.incr.decr.mget等 应用场景: String是最常用的数据类型,普通的key/value都可以归为此类,value其实不仅是String,也 ...

  7. sql读取 所有表、结构 描述

    需要:读取库里面所有 表.以及表描述. 列.列描述 create PROCEDURE [dbo].[ProGetAllTableName] AS BEGIN --开启事物 BEGIN TRAN tra ...

  8. get/post比较

    转载: https://www.oschina.net/news/77354/http-get-post-different https://www.cnblogs.com/wswang/p/6054 ...

  9. Alpha 冲刺 (9/10)

    目录 摘要 团队部分 个人部分 摘要 队名:小白吃 组长博客:hjj 作业博客:冲刺倒计时之9 团队部分 后敬甲(组长) 过去两天完成了哪些任务 答辩准备中 和大佬们跟进进度 接下来的计划 准备答辩 ...

  10. js的事件冒泡,事件捕获

      addEventListener() 方法可以指定 "useCapture" 参数来设置传递事件类型:false→冒泡       true→捕获       默认false. ...