码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 701. Insert into a Binary Search Tree

时间:2019-02-05 23:50:00      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:tco   lse   insert   main   bin   node   treenode   解决   二叉搜索树   

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 Binary Search Tree

标签:tco   lse   insert   main   bin   node   treenode   解决   二叉搜索树   

原文地址:https://www.cnblogs.com/rever/p/10353272.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!