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     }

     




  • 相关阅读:
    labVIEW学习——属性节点
    MATLAB学习
    WinForm中键盘按键问题
    TextBox的智能感知
    使用脚本操作UpdatePanel中控件的问题
    DBNull.Value,null,String.Empty之间的区别和联系
    Hotmail如何对已经存在的邮件地址进行更改?
    第一个hibernate项目
    html静态实现左边导航右边显示链接页面
    Struts2学习
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8487147.html
Copyright © 2011-2022 走看看