前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 701 Insert into a Binary Search Tree

LeetCode 701 Insert into a Binary Search Tree

作者头像
一份执着✘
发布2019-12-30 16:55:54
3520
发布2019-12-30 16:55:54
举报
文章被收录于专栏:赵俊的Java专栏赵俊的Java专栏

题意

给定一颗 二叉搜索树 的根节点,和一个要插入的值,将值插入进去,并返回根节点

  • 保证原树中不存在新值
  • 只要保证返回的树同样也是 二叉搜索树 即可

例 :

代码语言:javascript
复制
给予树:
        4 
       / \ 
      2   7 
     / \ 
    1   3 
并且要插入的值:5

您可以返回此 二叉搜索树

代码语言:javascript
复制
     4
   /   \
  2     7
 / \   /
1   3 5

这棵树也有效:

代码语言:javascript
复制
     5
   /   \
  2     7
 / \   
1   3
     \
      4

解法

因为是二叉搜索树,所以依次判断新值与每个节点的大小即可,大于当前节点,则判断此节点的右节点与新节点。小于当前节点,则判断此节点的左节点与新节点,直到子节点为空,那么再根据此节点的大小选择放到左侧还是右侧。

代码语言:javascript
复制
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode insertIntoBST(TreeNode root, int val) {
        if (root == null) {
            throw new IllegalArgumentException("Tree Root can not be empty");
        }
        TreeNode current = root;

        TreeNode preNode = null;
        while (current != null) {
            preNode = current;
            if (current.val < val) {
                current = current.right;
            } else if (current.val > val){
                current = current.left;
            }
        }

        if (preNode.val < val) {
            System.out.println("1");
            preNode.right = new TreeNode(val);
        } else {
            System.out.println("2");
            preNode.left = new TreeNode(val);
        }

        return root;
    }
}

Runtime: 1 ms, faster than 100.00% of Java online submissions for Insert into a Binary Search Tree. Memory Usage: 39.8 MB, less than 94.61% of Java online submissions for Insert into a Binary Search Tree.

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-03-26,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题意
  • 解法
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档