当前位置:网站首页>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;
}
};
边栏推荐
猜你喜欢
用PLSQL导出Oracle一个表
【Burning】It's time to show your true strength!Understand the technical highlights of the 2022 Huawei Developer Competition in one article
“我“是一名测试/开发程序员,小孙的内心独白......
Tencent continues to wield the "big knife" to reduce costs and increase efficiency, and free catering benefits for outsourced employees have been cut
leetcode:321. 拼接最大数
leetcode:325. 和等于k的最长子数组长度
JS中表单操作、addEventListener事件监听器
ArrayList 和 LinkedList 区别
shell学习
Install win7 virtual machine in Vmware and related simple knowledge
随机推荐
【GORM】模型关系-HasMany关系
【Burning】It's time to show your true strength!Understand the technical highlights of the 2022 Huawei Developer Competition in one article
&&、||、&、|
A1. Prefix Flip (Easy Version)
leetcode 38. 外观数列
【微信小程序开发(八)】音频背景音乐播放问题汇总
CGLIB源码易懂解析
xlrd 与 xlsxwritter 的基本操作
What is the stability of the quantitative trading interface system?
继承关系下构造方法的访问特点
大型分布式存储方案MinIO介绍,看完你就懂了!
D. Binary String To Subsequences
Bi Sheng Compiler Optimization: Lazy Code Motion
How to insist to use procedural system?
FileZilla搭建FTP服务器图解教程
A. Common Prefixes
R语言将列表数据转化为向量数据(使用unlist函数将列表数据转化为向量数据)
NodeJS使用JWT
UNI-APP_ monitor page scroll h5 monitor page scroll
What kind of mentality do you need to have when using the stock quantitative trading interface