Given a binary tree, find the length of the longest consecutive sequence path.
The path could be start and end at any node in the tree
Example
1
/
2 0
/
3
Return 4
// 0-1-2-3
分治法。和前一题根本思路一致,判断root.val和左右节点的val是否连续,以确定能否完成接龙。只是本题要记录的变为从root开始向下的最长increase序列和最长decrease序列!于是每次就能搭出从左到右的,最长增长序列与最长减小序列,与全局变量对比,记录。
/** * 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 int longestConsec = Integer.MIN_VALUE; private class ResultType{ public int incrs; public int decrs; public ResultType(int incrs, int decrs) { this.incrs = incrs; this.decrs = decrs; } } public int longestConsecutive2(TreeNode root) { // write your code here if (root == null) { return 0; } helper(root); return longestConsec; } //返回从root向下到叶子节点可以的最长的递增consecutive和递减consecutive public ResultType helper(TreeNode root) { if (root == null) { return new ResultType(0, 0); } ResultType left = helper(root.left); ResultType right = helper(root.right); int crtLeftIncrs = 1; int crtLeftDecrs = 1; int crtRightIncrs = 1; int crtRightDecrs = 1; if (root.left != null && root.left.val + 1 == root.val) { crtLeftDecrs = 1 + left.decrs; } if (root.left != null && root.left.val - 1 == root.val) { crtLeftIncrs = 1 + left.incrs; } if (root.right != null && root.right.val + 1 == root.val) { crtRightDecrs = 1 + right.decrs; } if (root.right != null && root.right.val - 1 == root.val) { crtRightIncrs = 1 + right.incrs; } // check the longest if (crtLeftIncrs + crtRightDecrs - 1 > longestConsec) { longestConsec = crtLeftIncrs + crtRightDecrs - 1; } if (crtLeftDecrs + crtRightIncrs - 1 > longestConsec) { longestConsec = crtLeftDecrs + crtRightIncrs - 1; } return new ResultType(Math.max(crtLeftIncrs, crtRightIncrs), Math.max(crtLeftDecrs, crtRightDecrs)); } }