给一个树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
标题“POJ2533-Longest Ordered Subsequence”是指北京大学在线判题系统POJ上的一道编程题目,其核心任务是寻找一个序列中最长的有序子序列。描述中的“解题报告+AC代码”表明这个压缩包包含了对这道问题的解答思路...
北大POJ2533-Longest Ordered Subsequence【O(nlogn)】
北大POJ2533-Longest Ordered Subsequence【O(n^2)】
特别是当我们需要比较多个字符串,并找出它们的最长公共前缀(Longest Common Prefix,简称LCP)时,这是一个在数据处理和搜索算法中经常出现的问题。LeetCode是一个编程面试准备的热门平台,它提供各种编程问题供...
题目"159-longest-substring-with-at-most-two-distinct"是LeetCode算法题目之一。本题要求解的是找出在给定字符串中,具有最多两个不同字符的最长子串的长度。 2. 题目要求: - 输入是一个字符串,保证只包含...
最长公共子序列(Longest Common Subsequence,LCS)是计算机科学中一种经典的字符串问题,主要涉及算法分析和设计,尤其是动态规划算法的应用。在这个压缩包文件"The-longest-public-son-sequence.rar_The Son"中,...
longest_streak = max(longest_streak, current_streak) # 更新最长连续序列长度 return longest_streak # 示例数组 print(longest_consecutive([100, 4, 200, 1, 3, 2])) # 输出应为4 ``` 以上代码就完整地...
其中,编号为32的题目"longest-valid-parentheses"是一个关于字符串处理的经典问题,要求编写代码找出给定的括号字符串中最长的有效括号子串长度。 在解决"longest-valid-parentheses"问题时,需要理解有效括号子串...
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
c c语言_leetcode题解之0300_longest_increasing_subsequence
java入门 java_leetcode题解之014_Longest_Common_Prefix
java入门 java_leetcode题解之005_Longest_Palindromic_Substring
c语言入门 c语言_leetcode题解之0516_longest_palindromic_subsequence
c语言入门 c语言_leetcode题解之1143_longest_common_subsequence
java入门 java_leetcode题解之003_Longest_Substring_Without_Repeating
本篇文章针对LeetCode题库中的第5题“最长回文子串(Longest Palindromic Substring)”给出C语言的解决方案。回文串是一个正读和反读都一样的字符串,在解决这个问题时,我们需要找到输入字符串中最长的回文子串。 ...
这个项目“Find-Longest-Word-Made-of-Other-Words”涉及到一个特定的排序问题:从一个单词列表中找出可以由其他单词组成的最长单词。这不仅涉及到排序,还涉及到字符串处理和算法设计。以下是对这个项目的详细解析...