Binary Tree Longest Consecutive Sequence
Analysis
这个结果是用Divid & Conquer 做的
1. Divid: tree->left child and right child
2. Conquer: when it is null, return 0
3. Merge:如果是sequence, 则现在的sequence的长度加一, 比较现在的subtree最长序列和已知序列,保留长的。
可以好好看看怎么不用全局变量完成题目
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { /** * @param root the root of binary tree * @return the length of the longest consecutive sequence path */ private class ResultType { int maxInSubtree; int maxFromRoot; public ResultType (int maxInSubtree, int maxFromRoot) { this.maxInSubtree = maxInSubtree; this.maxFromRoot = maxFromRoot; } } public int longestConsecutive(TreeNode root) { // Write your code here return helper(root).maxInSubtree; } private ResultType helper(TreeNode root) { if (root == null) { return new ResultType(0, 0); } ResultType left = helper(root.left); ResultType right = helper(root.right); //System.out.println(root.val); ResultType result = new ResultType(0, 1); if (root.left != null && root.val + 1 == root.left.val ) { result.maxFromRoot = Math.max(result.maxFromRoot, left.maxFromRoot + 1); } if (root.right != null && root.val + 1 == root.right.val) { result.maxFromRoot = Math.max(result.maxFromRoot, right.maxFromRoot + 1); } result.maxInSubtree = Math.max(result.maxFromRoot, Math.max(left.maxInSubtree, right.maxInSubtree)); return result; } }
posted on 2017-03-15 02:56 codingEskimo 阅读(88) 评论(0) 收藏 举报
浙公网安备 33010602011771号