给一个树root的pointer,树包含多个分支,树结构要自己创造。求一条最长路径。
例如(括号对应上面node)
树: 2
| | | |
5 7 3 6
(| | )( | )( | ) (| |)
6 3 2 4 5 8
|
3
返回3因为 (2-3-4) 这条线。优化要求时间O(n)
static class NTreeNode { int val; List<NTreeNode> children = new ArrayList<>(); } public int longestContinuousPath(NTreeNode root) { if(root == null) return 0; return longestContinuousPath(root, 1); } public int longestContinuousPath(NTreeNode root, int len) { int max = 0; for(NTreeNode child:root.children) { if(child == null) continue; int curLen = longestContinuousPath(child, child.val == root.val + 1 ? len + 1 : 1); max = Math.max(curLen, max); } return Math.max(max, len); }
相关推荐
c语言入门 c语言_leetcode题解之1372_longest_zigzag_path_in_a_binary_tree
c语言入门 c语言_leetcode题解03-longest-substring-without-repeating-characters
标题“POJ2533-Longest Ordered Subsequence”是指北京大学在线判题系统POJ上的一道编程题目,其核心任务是寻找一个序列中最长的有序子序列。描述中的“解题报告+AC代码”表明这个压缩包包含了对这道问题的解答思路...
c语言入门 c语言_leetcode题解05-longest-palindromic-substring.c
js js_leetcode题解3-longest-substring-without-repeating-characters.js
javascript js_leetcode题解之159-longest-substring-with-at-most-two-distinct
javascript js_leetcode题解之128-longest-consecutive-sequence.js
js js_leetcode题解之32-longest-valid-parentheses.js
js js_leetcode题解之14-longest-common-prefix.js
js js_leetcode题解之5-longest-palindromic-substring.js
c语言入门 C语言_leetcode题解之32-longest-valid-parentheses.c
c语言入门 C语言_leetcode题解之14-longest-common-prefix.c
北大POJ2533-Longest Ordered Subsequence【O(nlogn)】
北大POJ2533-Longest Ordered Subsequence【O(n^2)】
最长公共子序列(Longest Common Subsequence,LCS)是计算机科学中一种经典的字符串问题,主要涉及算法分析和设计,尤其是动态规划算法的应用。在这个压缩包文件"The-longest-public-son-sequence.rar_The Son"中,...
c c语言_leetcode 0014_longest_common_prefix.zip
c c语言_leetcode 0005_longest_palindromic_substring.zip
c c语言_leetcode 0003_longest_substring_without_repeat.zip
python python_leetcode题解之128_Longest_Consecutive_Sequence