zoukankan      html  css  js  c++  java
  • [LeetCode] 701. Insert into a Binary Search Tree

    Description

    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
    

    Analyse

    简单题,将节点插入BST,题目中保证了不会出现值相同的节点

    这里用了递归来做,要插入的节点大于root的值,就插入到root的右子树,,否则插入到root的左子树,如果左右子树为空,要插入的节点就成为新的左右子树

    TreeNode* insertIntoBST(TreeNode* root, int val)
    {
        if (root == NULL) return root;
        InsertIntoBSTInner(root, val);
        return root;
    }
    
    void InsertIntoBSTInner(TreeNode* root, int val)
    {
        if (root == NULL) return;
        if (val > root->val)
        {
            if (root->right == NULL)
            {
                TreeNode* node = new TreeNode(val);
                root->right = node;
            }
            else
            {
                InsertIntoBSTInner(root->right, val);
            }
        }
        else
        {
            if (root->left == NULL)
            {
                TreeNode* node = new TreeNode(val);
                root->left = node;
            }
            else
            {
                InsertIntoBSTInner(root->left, val);
            }
        }
    }
    

    把这段代码简化一下

    TreeNode* insertIntoBST(TreeNode* root, int val)
    {
        if (root == NULL)
        {
            TreeNode* node = new TreeNode(val);
            return node;
        }
    
        if (val > root->val)
        {
            root->right = insertIntoBST(root->right, val);
        }
        else
        {
            root->left = insertIntoBST(root->left, val);
        }
        return root;
    }
    
  • 相关阅读:
    Java 自动装箱与拆箱(Autoboxing and unboxing)【转】
    工厂方法和new
    java线程池【转】
    大型网站架构演化过程
    jsp el表达式
    GC垃圾回收
    mysql语句
    String StringBuilder StringBuffer
    粉丝关注数据库表的设计
    ECharts图表之柱状折线混合图
  • 原文地址:https://www.cnblogs.com/arcsinw/p/10289445.html
Copyright © 2011-2022 走看看