zoukankan      html  css  js  c++  java
  • LC.298.Binary Tree Longest Consecutive Sequence

    https://leetcode.com/problems/binary-tree-longest-consecutive-sequence/description/
    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).

    For example,
    1

    3
    /
    2 4

    5
    Longest consecutive sequence path is 3-4-5, so return 3.
    2

    3
    /
    2
    /
    1
    Longest consecutive sequence path is 2-3,not3-2-1, so return 2.
    PATH 还是从头走到能走的, 不是从半路 开始走
    如果 不满足条件 把当前的MAX = 1
    HELPER 函数想到了,全局变量想到了,helper 和 主函数的关系这块儿还需要多做题
    time: o(n) space: o(n)
     1  int res =0;
     2     public int longestConsecutive(TreeNode root) {
     3         if (root == null) return res;
     4         helper(root,0,root.val);
     5         return res ;
     6     }
     7 
     8     private void helper(TreeNode root, int max, int target) {
     9         //corner case
    10         if (root == null) return ;
    11         if (root.val == target){
    12             max++;
    13         } else{
    14             max = 1 ;
    15         }
    16         //这里很巧妙的随时更新 RES 这样就不需要HELPER 函数弄返回值
    17         res = Math.max(res, max) ;
    18         //细节: MAX 这里是 INT 不是 REF 所以不需要像PATH SUM II 里面 最后一步要 REMOVE
    19        //换句话说,如果 Max= 2  先走LEFT, left只是对它那一层的 Max 进行改变,
    20         // 沿着左边走到最后 跳出后,走RIGHT 时,MAX 还是 2!!!
    21         helper(root.left,max, root.val+1);
    22         helper(root.right,max, root.val+1);
    23     }

     




  • 相关阅读:
    windows mobile 上文件压缩与解压缩之二
    windows mobile多线程示例
    JDK 1.5 环境变量的配置
    PDA连接远程数据库的三种解决方案(转)
    Windows Mobile连接数据库的几种方式(转)
    .Net Compact Framework 调用 Java WebService
    MyEclipse 中文乱码
    Tomcat环境变量配置
    XML on Windows Mobile (C#)
    从VS2005项目转换为VS2008项目(C#版)
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8487147.html
Copyright © 2011-2022 走看看