Description
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
Example
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
5/10/2017
算法班,这道题其实已经不是binary tree了,不过至少是从那里演化而来。
未经验证,注意第44行,3方面比较
起始值为0还是1跟第44行+1还是-1有关。
1 /** 2 * Definition for a multi tree node. 3 * public class MultiTreeNode { 4 * int val; 5 * List<TreeNode> children; 6 * MultiTreeNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 /** 11 * @param root the root of k-ary tree 12 * @return the length of the longest consecutive sequence path 13 */ 14 class Result { 15 int maxLength; 16 int maxUp; 17 int maxDown; 18 Result(int maxLength, int maxUp, int maxDown) { 19 this.maxLength = maxLength; 20 this.maxUp = maxUp; 21 this.maxDown = maxDown; 22 } 23 } 24 public int longestConsecutive3(MultiTreeNode root) { 25 // Write your code here 26 if (root == null) return 0; 27 Result ret = longestPath(root); 28 return ret.maxLength; 29 } 30 31 private void longestPath(MultiTreeNode root) { 32 if (root == null) { 33 return new Result(0, 0, 0); 34 } 35 int maxLength = 0, maxUp = 0, maxDown = 0; 36 for (TreeNode child: root.children) { 37 Result tmp = longestPath(child); 38 if (child.val - 1 == root.val) { 39 maxUp = Math.max(maxUp, tmp.maxUp + 1); 40 } 41 if (child.va + 1 == root.val) { 42 maxDown = Math.max(maxDown, tmp.maxDown + 1); 43 } 44 maxLength = Math.max(Math.max(maxLength, tmp.maxLength), maxUp + maxDown + 1); 45 } 46 return new Result(maxLength, maxUp, maxDown); 47 } 48 49 }