• 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
  • 相关阅读:
    Markdown语法
    Hello World
    sql笔试题-1
    解决高版本vm打开虚拟机报错
    zookeeper启动闪退
    java找出1~1000中素数的三种方式
    Java中更精确的计时
    vue系列之调试工具(vue-devtools)
    vue系列之npm命令错误
    vue系列之安装基础环境
  • 原文地址:https://www.cnblogs.com/immiao0319/p/9449218.html
Copyright © 2020-2023  润新知