[LintCode] 619 Binary Tree Longest Consecutive Sequence III 二叉树最长连续序列 III
2024-09-28 09:56:17
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
最新文章
- 超棒的javascript移动触摸设备开发类库-QUOjs
- java系列-安装MySql(三)
- Java Web include指令和动作的区别
- PPAS Migration Toolkit document
- 基于管道通知的百万并发长连接server模型
- python自动开发之第十二天
- python命令行运行在win和Linux系统的不同
- SQL 2008 数据库迁移
- [Network]Wireless and Mobile
- Git 常用命令速查表(三)
- JDK版本会影响项目部署
- c# 数组简述
- Java安装及基础01
- 【MySQL】5.7 复制
- Dream team: Stacking for combining classifiers梦之队:组合分类器
- Go学习笔记02-基本语法
- VirtualBox 扩展包卸载或安装失败(VERR_ALREADY_EXISTS)(转)
- Infopath 2010 接收SQL Server数据
- 【架构】ServiceMesh初步了解
- SQL Expression Language Tutorial 学习笔记一
热门文章
- nginx反向代理 报错:Error during WebSocket handshake: Unexpected response code: 403
- PHP 面试服务器优化和大数据
- Luogu P3489 [POI2009]WIE-Hexer 最短路
- LOJ#565. 「LibreOJ Round #10」mathematican 的二进制 分治,FFT,概率期望
- 浅析TCP三次握手及四次挥手
- bootstrap table插件动态加载表头
- jquery选择器(1)
- RabbitMQ入门学习系列(六) Exchange的Topic类型
- php手记之08-tp5中间件
- Qt 操作QDomDocument对象修改节点