• 669. Trim a Binary Search Tree669.修剪二进制搜索树


    [抄题]:

    Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that all its elements lies in [L, R] (R >= L). You might need to change the root of the tree, so the result should return the new root of the trimmed binary search tree.

    Example 1:

    Input: 
        1
       / 
      0   2
    
      L = 1
      R = 2
    
    Output: 
        1
          
           2
    

    Example 2:

    Input: 
        3
       / 
      0   4
       
        2
       /
      1
    
      L = 1
      R = 3
    
    Output: 
          3
         / 
       2   
      /
     1

     [暴力解法]:

    时间分析:

    空间分析:

     [优化后]:

    时间分析:

    空间分析:

    [奇葩输出条件]:

    [奇葩corner case]:

    超出左边界,就要去右边找。反之亦然。

    [思维问题]:

    [英文数据结构或算法,为什么不用别的数据结构或算法]:

    [一句话思路]:

    在LR的范围之内,我才允许中序遍历.
    -不是中序啊,就是树都有的一般的DC

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    [二刷]:

    不知道为啥是dc,很明显是一个外形的题目啊。
    是不是因为要返回?是的吧,反正大部分都是DC.

    [三刷]:

    啥思路吧反正
    既然是有“范围”这种特殊要求的题目,就在参数里加上范围就行了:小于左边界就去右边比较,大于右边界就去左边

    [四刷]:

    划分的这一步是需要返回的。
    实现的不需要返回。指定左边、右边分别是什么

    [五刷]:

      [五分钟肉眼debug的结果]:

    [总结]:

    [复杂度]:Time complexity: O() Space complexity: O()

    [算法思想:迭代/递归]:

    [关键模板化代码]:

    [其他解法]:

    [Follow Up]:

    [LC给出的题目变变变]:

     [代码风格] :

     [是否头一次写此类driver funcion的代码] :

     [潜台词] :

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode() {}
     *     TreeNode(int val) { this.val = val; }
     *     TreeNode(int val, TreeNode left, TreeNode right) {
     *         this.val = val;
     *         this.left = left;
     *         this.right = right;
     *     }
     * }
     */
    class Solution {
        public TreeNode trimBST(TreeNode root, int L, int R) {
            //边界情况总是需要返回才行的
            if (root == null) {
                return null;
            }
            
            if (root.val < L) {
                return trimBST(root.right, L, R);
            }
            
            if (root.val > R) {
                return trimBST(root.left, L, R);
            }
            
            root.left = trimBST(root.left, L, R);
            root.right = trimBST(root.right, L, R);
            
            return root;
        }
    }
    View Code
  • 相关阅读:
    Thrift --- 支持双向通信
    Go -- 配置监控系统
    Go -- RPC 之 Thrift
    Go -- 一致性哈希算法
    Go -- runtime.Gosched()的作用分析
    Go -- import使用及. _的作用解析
    BNF 和 ABNF 扩充巴科斯范式 了解
    转 HTTP.SYS 详解
    转 HTTP/2: The Long-Awaited Sequel
    网站分析
  • 原文地址:https://www.cnblogs.com/immiao0319/p/12940850.html
Copyright © 2020-2023  润新知