当前位置:网站首页>Leetcode 701. 二叉搜索树中的插入操作
Leetcode 701. 二叉搜索树中的插入操作
2022-08-09 22:05:00 【LuZhouShiLi】
Leetcode 701. 二叉搜索树中的插入操作
题目
给定二叉搜索树(BST)的根节点 root 和要插入树中的值 value ,将值插入二叉搜索树。 返回插入后二叉搜索树的根节点。 输入数据 保证 ,新值和原始二叉搜索树中的任意节点值都不同。
注意,可能存在多种有效的插入方式,只要树在插入后仍保持为二叉搜索树即可。 你可以返回 任意有效的结果 。
思路
- 确定递归的参数和返回值:参数就是根节点指针,以及要插入的元素,递归函数有返回值,可以利用返回值完成新加入的节点与其父节点的赋值操作
- 确定终止条件:当前便利的节点是NULL,则该节点就是要插入节点的位置,并把插入的节点返回
- 确定单层递归的逻辑:搜索树是有方向的,可以根据插入元素的数值决定递归的方向
代码
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(root == NULL)
{
// 递归出口
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;
}
};
边栏推荐
猜你喜欢
随机推荐
MySQL——JDBC
大型分布式存储方案MinIO介绍,看完你就懂了!
Tencent continues to wield the "big knife" to reduce costs and increase efficiency, and free catering benefits for outsourced employees have been cut
Space not freed after TRUNCATE table
【服务器数据恢复】SAN LUN映射出错导致文件系统数据丢失的数据恢复案例
LeetCode_2632_字符串压缩
The 2022-8-9 sixth group of input and output streams
charts.js插件实现的散点图样式
R语言拟合ARIMA模型并使用拟合模型进行预测推理:使用forecast函数计算ARIMA模型未来值(包含时间点、预测值、两个置信区间)
Arcgis工具箱无法使用,显示“XML包含错误“的解决方法
daemon
使用股票量化交易接口需要具备怎么样的心态
mysql 、pg 查询日期处理
Js fifteen interview questions (with answers)
pip 离线到内网安装包
leetcode brush questions diary Calculate the number of elements on the right that is less than the current element
Presto Event Listener开发
Interviewer: How to deal with Redis big key?
D. Binary String To Subsequences
继承关系下构造方法的访问特点









