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;
    }
    
  • 相关阅读:
    Android学习地址
    Android动画设计源码地址
    chromeWebBrowser之浏览器开发
    win8.1蓝屏解决
    打包应用程序
    win8.1解决鼠标右键反应慢的问题
    Rewrite服务器和robots文件屏蔽动态页面
    第08组 Alpha事后诸葛亮
    第08组 Alpha冲刺(6/6)
    第08组 Alpha冲刺(5/6)
  • 原文地址:https://www.cnblogs.com/arcsinw/p/10289445.html
Copyright © 2011-2022 走看看