美文网首页
[LeetCode] 701. Insert into a Bi

[LeetCode] 701. Insert into a Bi

作者: 九里 | 来源:发表于2019-08-05 11:00 被阅读0次

    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;
        }
        }
    

    相关文章

      网友评论

          本文标题:[LeetCode] 701. Insert into a Bi

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