It's follow up problem for Binary Tree Longest Consecutive Sequence II
Given a k-ary tree
, find the length of the longest consecutive sequence path.
The path could be start and end at any node in the tree
xample
An example of test data: k-ary tree 5<6<7<>,5<>,8<>>,4<3<>,5<>,3<>>>
, denote the following structure:
5
/
6 4
/| /|
7 5 8 3 5 3
Return 5, // 3-4-5-6-7
分治法+全局变量监控。这题只是数据结构改变了,子方法和上面的是一样的。找root+子树的最长increase与最长decrease,加起来-1就是本层的最长root了。
/** * Definition for a multi tree node. * public class MultiTreeNode { * int val; * List<TreeNode> children; * MultiTreeNode(int x) { val = x; } * } */ public class Solution { /** * @param root the root of k-ary tree * @return the length of the longest consecutive sequence path */ private int longestConsec = Integer.MIN_VALUE; private class ResultType { int incrs; int decrs; public ResultType(int incrs, int decrs) { this.incrs = incrs; this.decrs = decrs; } } public int longestConsecutive3(MultiTreeNode root) { // Write your code here if (root == null) { return 0; } helper(root); return longestConsec; } private ResultType helper(MultiTreeNode root) { List<MultiTreeNode> children = root.children; int crtIncrs = 1; int crtDecrs = 1; for (MultiTreeNode child : children) { ResultType childResult = helper(child); if (root.val + 1 == child.val) { crtIncrs = Math.max(1 + childResult.incrs, crtIncrs); } if (root.val - 1 == child.val) { crtDecrs = Math.max(1 + childResult.decrs, crtDecrs); } } if (crtIncrs + crtDecrs - 1 > longestConsec) { longestConsec = crtIncrs + crtDecrs - 1; } return new ResultType(crtIncrs, crtDecrs); } }