码迷,mamicode.com
首页 > 其他好文 > 详细

298.Binary Tree Longest Consecutive Sequence

时间:2016-07-03 11:44:56      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:

    /*
     * 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

标签:

原文地址:http://www.cnblogs.com/zmyvszk/p/5637029.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!