给定二叉搜索树(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==NULL){
TreeNode* node=new TreeNode(val);
return node;
}
if(root->val>val)root->left=insertIntoBST(root->left,val);
else if(root->val<val)root->right=insertIntoBST(root->right,val);
return root;
}
};
无返回值递归:
/**
* 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 {
private:
TreeNode* parent;
void traversal(TreeNode* cur,int val){
if(cur==NULL){
TreeNode* node=new TreeNode(val);
//判断插入点在前节点的左右
if(parent->val>val)parent->left=node;
else parent->right=node;
return;
}
//前一节点,无返回值,必须定义
parent=cur;
//遍历二叉搜索树
if(cur->val>val)traversal(cur->left,val);
if(cur->val<val)traversal(cur->right,val);
return;
}
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
parent=new TreeNode(0);
if(root==NULL){
root=new TreeNode(val);
}
traversal(root,val);
return root;
}
};
迭代法:
/**
* 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) {
//如果root为空,则直接插入
if(root==NULL){
TreeNode* node=new TreeNode(val);
return node;
}
//记录新节点
TreeNode* cur=root;
//记录上一个节点
TreeNode* parent=root;
//遍历二叉搜索树
while(cur!=NULL){
//记录上一个节点
parent=cur;
//如果新节点访问的数值大于要插入的数值,则向左遍历
if(cur->val>val)cur=cur->left;
//反之如下
else cur=cur->right;
}
//定义要插入的新节点
TreeNode* node=new TreeNode(val);
//此时parent节点赋值
if(val<parent->val)parent->left=node;
else parent->right=node;
return root;
}
};