/**
* 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)
{
root=new TreeNode(val);
}
if(val>root->val)
{
root->right=insertIntoBST(root->right,val);
}
if(val<root->val)
{
root->left=insertIntoBST(root->left,val);
}
return root;
}
};
LeetCode:701. 二叉搜索树中的插入操作
最新推荐文章于 2025-05-27 02:00:00 发布
本文详细介绍了如何在二叉搜索树中插入一个新节点。通过递归算法,确保树的性质得以保持,即所有左子树上的节点值小于根节点,所有右子树上的节点值大于根节点。
3万+

被折叠的 条评论
为什么被折叠?



