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

解法:和Binary Tree Longest Consecutive Sequence II一样的做法。II只要check一下left和right。这题因为有多个子节点,所以要用一个循环来check所有。

Java:

 class ResultType {
int globalMax;
int maxUp;
int maxDown;
public ResultType(int globalMax, int maxUp, int maxDown) {
this.globalMax = globalMax;
this.maxUp = maxUp;
this.maxDown = maxDown;
}
} public int longestConsecutive3(MultiTreeNode root) {
return helper(root).globalMax;
} public ResultType helper(MultiTreeNode root) { if (root == null) {
return new ResultType(0, 0, 0);
} int maxUp = 0;
int maxDown = 0;
int max = Integer.MIN_VALUE; for (MultiTreeNode child : root.children) { if (child == null) {
continue;
} ResultType childResult = helper(child);
if (child.val + 1 == root.val) {
maxDown = Math.max(maxDown, childResult.maxDown + 1);
} if (child.val - 1 == root.val) {
maxUp = Math.max(maxUp, childResult.maxUp + 1);
} max = Math.max(Math.max(max, childResult.globalMax), maxUp + maxDown + 1);
} return new ResultType(max, maxUp, maxDown);
}

  

类似题目:

[LeetCode] 298. Binary Tree Longest Consecutive Sequence 二叉树最长连续序列

[LeetCode] 549. Binary Tree Longest Consecutive Sequence II 二叉树最长连续序列之 II

最新文章

  1. 超棒的javascript移动触摸设备开发类库-QUOjs
  2. java系列-安装MySql(三)
  3. Java Web include指令和动作的区别
  4. PPAS Migration Toolkit document
  5. 基于管道通知的百万并发长连接server模型
  6. python自动开发之第十二天
  7. python命令行运行在win和Linux系统的不同
  8. SQL 2008 数据库迁移
  9. [Network]Wireless and Mobile
  10. Git 常用命令速查表(三)
  11. JDK版本会影响项目部署
  12. c# 数组简述
  13. Java安装及基础01
  14. 【MySQL】5.7 复制
  15. Dream team: Stacking for combining classifiers梦之队:组合分类器
  16. Go学习笔记02-基本语法
  17. VirtualBox 扩展包卸载或安装失败(VERR_ALREADY_EXISTS)(转)
  18. Infopath 2010 接收SQL Server数据
  19. 【架构】ServiceMesh初步了解
  20. SQL Expression Language Tutorial 学习笔记一

热门文章

  1. nginx反向代理 报错:Error during WebSocket handshake: Unexpected response code: 403
  2. PHP 面试服务器优化和大数据
  3. Luogu P3489 [POI2009]WIE-Hexer 最短路
  4. LOJ#565. 「LibreOJ Round #10」mathematican 的二进制 分治,FFT,概率期望
  5. 浅析TCP三次握手及四次挥手
  6. bootstrap table插件动态加载表头
  7. jquery选择器(1)
  8. RabbitMQ入门学习系列(六) Exchange的Topic类型
  9. php手记之08-tp5中间件
  10. Qt 操作QDomDocument对象修改节点