298.Binary Tree Longest Consecutive Sequence

Posted 我的名字叫周周

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了298.Binary Tree Longest Consecutive Sequence相关的知识,希望对你有一定的参考价值。

    /*
     * 298.Binary Tree Longest Consecutive Sequence
     *  2016-7-2 by Mingyang
     *  完全国产自主化的代码,利用了自底向上的思想,先从最底下的节点网上走,另外设置一个全局变量res随时更新
     *  跟uniq trees那道题目类似,非常棒!
     *  时间肯定是n,跟post order差不多的原理,空间也是n,因为用了recursion
     *  The extra space comes from implicit stack space due to recursion. 
     *  For a skewed binary tree, the recursion could go up to nn levels deep.
     */
      public int res=0;
      public int longestConsecutive(TreeNode root) {
            longestHelper(root);
            return res;
        }
      public int longestHelper(TreeNode root){
            if(root==null)
              return 0;
            int left=longestHelper(root.left);
            int right=longestHelper(root.right);
            int current=1;
            if(root.left!=null&&root.val+1==root.left.val){
                current=left+1;
            }
            if(root.right!=null&&root.val+1==root.right.val){
                current=Math.max(current,right+1);
            }
            res=Math.max(res,current);
            return current;
        }

 

以上是关于298.Binary Tree Longest Consecutive Sequence的主要内容,如果未能解决你的问题,请参考以下文章

298. Binary Tree Longest Consecutive Sequence

[LC] 298. Binary Tree Longest Consecutive Sequence

298.Binary Tree Longest Consecutive Sequence

[Locked] Binary Tree Longest Consecutive Sequence

Binary Tree Longest Consecutive Sequence

LeetCode - Binary Tree Longest Consecutive Sequence