• [LeetCode] 701. Insert into a Binary Search Tree


    Given the root node of a binary search tree (BST) and a value to be inserted into the tree, insert the value into the BST. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.

    Note that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.

    For example,

    Given the tree:
            4
           / 
          2   7
         / 
        1   3
    And the value to insert: 5
    

    You can return this binary search tree:

             4
           /   
          2     7
         /    /
        1   3 5
    

    This tree is also valid:

             5
           /   
          2     7
         /    
        1   3
             
              4
    

    Solution:

    解决这个题目需要了解一下BST二叉搜索树的知识。BST是二叉树的一种形式,需要满足下面的几个条件。

    1.满足二叉树,只有两个子结点

    2.所有结点的值是唯一的

    3.左结点的值小于父结点的值,右结点的值大于父结点的值

    了解了BST的知识我们再来看如何对二叉树进行插入操作。因为二叉树的操作肯定是一个递归或者迭代的操作。所以对于任意的root结点进行插入操作,我们应该先比较插入值的大小跟root值的大小。如果大于root的值就插入到右边,反之插入到左边。下面给出用简单递归的方法实现:

    class Solution {
        public TreeNode insertIntoBST(TreeNode root, int val) {
            TreeNode node=new TreeNode(val);
            if(root==null) return node;
            if(root.val>val){
                  if(root.left==null){
                root.left=node;
                  }else{
                root.left= insertIntoBST(root.left,val);
                  }
            }
            else{
                if (root.right==null){
                  root.right=node;}
                else{
                    root.right=insertIntoBST(root.right,val);
                }
            }
            return root;
        }
        }
  • 相关阅读:
    JAVA-jar包下载地址
    JAVA-Eclipse中web-inf和meta-inf文件夹
    【转载】JAVA-dynamic web module与tomcat
    判断二叉树是不是平衡
    二叉树的深度
    二叉搜索树的后序遍历序列
    数对之差的最大值
    字符串的组合
    求二元查找树的镜像
    字符串的排列
  • 原文地址:https://www.cnblogs.com/rever/p/10353272.html
Copyright © 2020-2023  润新知