【LeetCode 45】701.二叉搜索树中的插入操作

简介: 【LeetCode 45】701.二叉搜索树中的插入操作

一、题意

二、解答过程

在二叉搜索树中插入节点,只需要遍历二叉搜索树即可,不需要改变它的结构,遍历当然用到递归

class Solution {
public://1.
    TreeNode* insertIntoBST(TreeNode* root, int val) {
        //2.
        if(root==NULL)
        {
            TreeNode *node=new TreeNode(val);
            return node;
        }
        //3.搜索树是有方向的,可以根据插入元素的数值决定递归方向
        //遍历这条边
        if(root->val>val) root->left=insertIntoBST(root->left,val);
        if(root->val<val) root->right=insertIntoBST(root->right,val);
        return root;
    }
};


目录
相关文章
|
3天前
【LeetCode 44】235.二叉搜索树的最近公共祖先
【LeetCode 44】235.二叉搜索树的最近公共祖先
7 1
|
3天前
【LeetCode 48】108.将有序数组转换为二叉搜索树
【LeetCode 48】108.将有序数组转换为二叉搜索树
10 0
|
3天前
【LeetCode 47】669.修剪二叉搜索树
【LeetCode 47】669.修剪二叉搜索树
5 0
|
3天前
【LeetCode 46】450.删除二叉搜索树的节点
【LeetCode 46】450.删除二叉搜索树的节点
5 0
|
3天前
【LeetCode 42】501.二叉搜索树中的众数
【LeetCode 42】501.二叉搜索树中的众数
4 0
|
3天前
【LeetCode 41】530.二叉搜索树的最小绝对差
【LeetCode 41】530.二叉搜索树的最小绝对差
5 0
|
3天前
【LeetCode 40】98.验证二叉搜索树
【LeetCode 40】98.验证二叉搜索树
5 0
|
3天前
【LeetCode 39】700.二叉搜索树中的搜索
【LeetCode 39】700.二叉搜索树中的搜索
5 0
|
4月前
|
机器学习/深度学习 存储 算法
LeetCode 题目 95:从递归到动态规划实现 不同的二叉搜索树 II
LeetCode 题目 95:从递归到动态规划实现 不同的二叉搜索树 II
|
2月前
|
Python
【Leetcode刷题Python】450. 删除二叉搜索树中的节点
LeetCode上538号问题"把二叉搜索树转换为累加树"的Python实现,使用反向中序遍历并记录节点值之和来更新每个节点的新值。
34 4
【Leetcode刷题Python】450. 删除二叉搜索树中的节点