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
  • 相关阅读:
    湘潭大学 Hurry Up 三分,求凹函数的最小值问题
    hdu 1166 线段树 单点修改 + 询问区间求和 (线段树模板)
    hdu 1166 树状数组(模板) 更改点值+求区间和
    getline
    poj 1873 The Fortified Forest 凸包+位运算枚举 world final 水题
    C# 代码操作XML(增、删、改)
    C# Socket服务端与客户端通信(包含大文件的断点传输)
    MD5 十六进制加密
    C# 面向对象——多态
    C# 面向对象——继承
  • 原文地址:https://www.cnblogs.com/immiao0319/p/9449218.html
Copyright © 2011-2022 走看看