• [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;
    }
    
  • 相关阅读:
    XMPP资源绑定(Resource Binding)与单台设备登录控制
    解决Eclipse建立Maven项目后无src/main/java资源文件夹的办法
    quartz做集群配置较短的时间间隔会重复执行任务的问题
    同一服务器部署多个tomcat时的端口号修改详情
    Java RSA加密算法生成公钥和私钥
    CSS3动画(重要)
    CSS3 过渡
    CSS3 3D 转换
    CSS3 2D 转换
    CSS3 文本效果(阴影)
  • 原文地址:https://www.cnblogs.com/arcsinw/p/10289445.html
Copyright © 2020-2023  润新知