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     }

     




  • 相关阅读:
    P2602 [ZJOI2010]数字计数
    P2657 [SCOI2009] windy 数
    Gym
    B
    Problem E The League of Sequence Designers
    C. Vladik and fractions
    hdu6069
    hdu 6096
    30道经典面试题,靠它我在一线拿到了20k的前端开发工程师岗位
    【面经分享】互联网寒冬,7面阿里,终获Offer!
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8487147.html
Copyright © 2011-2022 走看看