当前位置:网站首页>【LeetCode】701.二叉搜索树中的插入操作
【LeetCode】701.二叉搜索树中的插入操作
2022-08-04 10:50:00 【酥酥~】
题目
给定二叉搜索树(BST)的根节点 root 和要插入树中的值 value ,将值插入二叉搜索树。 返回插入后二叉搜索树的根节点。 输入数据 保证 ,新值和原始二叉搜索树中的任意节点值都不同。
注意,可能存在多种有效的插入方式,只要树在插入后仍保持为二叉搜索树即可。 你可以返回 任意有效的结果 。
示例 1:
输入:root = [4,2,7,1,3], val = 5
输出:[4,2,7,1,3,5]
解释:另一个满足题目要求可以通过的树是:
示例 2:
输入:root = [40,20,60,10,30,50,70], val = 25
输出:[40,20,60,10,30,50,70,null,null,25]
示例 3:
输入:root = [4,2,7,1,3,null,null,null,null,null,null], val = 5
输出:[4,2,7,1,3,5]
提示:
树中的节点数将在 [0, 104]的范围内。
-108 <= Node.val <= 108
所有值 Node.val 是 独一无二 的。
-108 <= val <= 108
保证 val 在原始BST中不存在。
题解
/** * 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 == nullptr)
return new TreeNode(val);
TreeNode* node = root;
while(node)
{
if(val < node->val)
{
if(node->left)
node = node->left;
else
{
node->left = new TreeNode(val);
break;
}
}
else
{
if(node->right)
node = node->right;
else
{
node->right = new TreeNode(val);
break;
}
}
}
return root;
}
};
递归
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(root == nullptr)
return new TreeNode(val);
if(val < root->val)
root->left = insertIntoBST(root->left,val);
else
root->right = insertIntoBST(root->right,val);
return root;
}
};
边栏推荐
猜你喜欢

iMeta | 百度认证完成,搜索“iMeta”直达出版社主页和投稿链接

粤黔协作,山海同心!578种贵州特色农产品走进粤港澳大湾区

Graphic and text hands-on tutorial--ESP32 MQTT docking EMQX local server (VSCODE+ESP-IDF)

Jenkins使用手册(1) —— 软件安装

What is the principle of thermal imaging temperature measurement?Do you know?

Win11 file types, how to change?Win11 modify the file suffix

C#/VB.NET:在 Word 中设置文本对齐方式

zabbix deployment

Maple 2022 software installation package download and installation tutorial

低代码是开发的未来吗?浅谈低代码开发平台的发展现状及未来趋势
随机推荐
图文手把手教程--ESP32 一键配网(Smartconfig、Airkiss)
深度学习100例 —— 卷积神经网络(CNN)天气识别
SkiaSharp 之 WPF 自绘 粒子花园(案例版)
Multimedia and Internet of Things technology make the version "live" 129 vinyl records "Centennial Voice"
MySQL 45 讲 | 10 MySQL为什么有时候会选错索引?
iMeta | 德国国家肿瘤中心顾祖光发表复杂热图(ComplexHeatmap)可视化方法
粤黔协作,山海同心!578种贵州特色农产品走进粤港澳大湾区
热成像测温的原理是什么呢?你知道吗?
无代码平台数字入门教程
What is the principle of thermal imaging temperature measurement?Do you know?
STM32前言知识总结
There are 12 balls, including 11 weight, only one, don't know is light or heavy. Three times in balance scales, find out the ball.
高级转录组分析和R数据可视化火热报名中(2022.10)
Super Learning Method
Win11 file types, how to change?Win11 modify the file suffix
MySQL:面试问的范式设计
Four ways to traverse a Map
Events in August | 51CTO's 17th Anniversary Celebration, post a blog post to get gifts such as tea sets/notebooks/T-shirts!
Learn to use the basic interface of set and map
iMeta | 百度认证完成,搜索“iMeta”直达出版社主页和投稿链接