美文网首页
LeetCode 第701题:二叉搜索树中的插入操作

LeetCode 第701题:二叉搜索树中的插入操作

作者: 放开那个BUG | 来源:发表于2020-10-18 14:44 被阅读0次

1、前言

题目描述

2、思路

还是使用二叉搜索树的框架,大于 val 只向左搜索,小于 val 值向右搜索。

3、代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode insertIntoBST(TreeNode root, int val) {
        if(root == null){
            return new TreeNode(val);
        }

        if(val < root.val){
            root.left = insertIntoBST(root.left, val);
        }else{
            root.right = insertIntoBST(root.right, val);
        }

        return root;
    }
}

相关文章

网友评论

      本文标题:LeetCode 第701题:二叉搜索树中的插入操作

      本文链接:https://www.haomeiwen.com/subject/addorktx.html