zoukankan      html  css  js  c++  java
  • 298. Binary Tree Longest Consecutive Sequence最长连续序列

    [抄题]:

    Given a binary tree, find the length of the longest consecutive sequence path.

    The path refers to any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The longest consecutive path need to be from parent to child (cannot be the reverse).

    Example 1:

    Input:
    
       1
        
         3
        / 
       2   4
            
             5
    
    Output: 3
    
    Explanation: Longest consecutive sequence path is 3-4-5, so return 3.

    Example 2:

    Input:
    
       2
        
         3
        / 
       2    
      / 
     1
    
    Output: 2 
    
    Explanation: Longest consecutive sequence path is 2-3, not 3-2-1, so return 2.

     [暴力解法]:

    时间分析:

    空间分析:

     [优化后]:

    时间分析:

    空间分析:

    [奇葩输出条件]:

    [奇葩corner case]:

    [思维问题]:

    不知道怎么比较左右两边的最大值:居然连dc的精髓都忘了,就写一个表达式,然后我用Max,让它自己搜出来就好了

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

    [一句话思路]:

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

    [画图]:

    [一刷]:

    val是上一个节点的val,所以root要低一级。主函数中是root.left root.right

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

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

    [总结]:

    需要统计个数时,参数就是节点数count

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

    [算法思想:迭代/递归/分治/贪心]:

    [关键模板化代码]:

    [其他解法]:

    [Follow Up]:

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

     [代码风格] :

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

     [潜台词] :

    class Solution {
        public int longestConsecutive(TreeNode root) {
            //corner case
            if (root == null) return 0;
            
            //return
            return Math.max(dfs(root.left, root.val, 1), dfs(root.right, root.val, 1));
        }
        
        public int dfs(TreeNode root, int val, int count) {
            //exit when root is null
            if (root == null) return count;
            
            //renew count, left, right
            count = (root.val == val + 1) ? count + 1 : 1;
            int left = dfs(root.left, root.val, count);
            int right = dfs(root.right, root.val, count);
            
            //compare and return
            return Math.max(Math.max(left, right), count);
        }
    }
    View Code
  • 相关阅读:
    redis接入sentinelPool的配置
    02.Redis主从集群的Sentinel配置
    淘宝大秒系统设计详解
    关于Thread.currentThread()和this的差异
    App开放接口api安全性—Token签名sign的设计与实现
    使用Spring Session做分布式会话管理
    PowerDesigner 15.1 安装步骤详细图解及破解
    解密ThreadLocal
    深入分析 ThreadLocal 内存泄漏问题
    一个经典例子让你彻彻底底理解java回调机制
  • 原文地址:https://www.cnblogs.com/immiao0319/p/9449218.html
Copyright © 2011-2022 走看看