标签:
/* * 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