JavaShowAlgorithm-Binary Tree Longest Consecutive Sequence
来源:互联网 发布:如何自学软件测试 编辑:程序博客网 时间:2024/06/05 01:03
Given a binary tree, find the length of the longest consecutive sequence path.
The path refers to any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The longest consecutive path need to be from parent to child (cannot be the reverse).
For example,
1 \ 3 / \ 2 4 \ 5
Longest consecutive sequence path is 3-4-5
, so return 3.
2 \ 3 / 2 / 1
Longest consecutive sequence path is 2-3
,not3-2-1
, so return 2.
递归法
复杂度
时间O(n) 空间O(h)
思路
因为要找最长的连续路径,我们在遍历树的时候需要两个信息,一是目前连起来的路径有多长,二是目前路径的上一个节点的值。我们通过递归把这些信息代入,然后通过返回值返回一个最大的就行了。这种需要遍历二叉树,然后又需要之前信息的题目思路都差不多,比如Maximum Depth of Binary Tree和Binary Tree Maximum Path Sum。
代码
public class Solution { public int longestConsecutive(TreeNode root) { if(root == null){ return 0; } return findLongest(root, 0, root.val - 1); } private int findLongest(TreeNode root, int length, int preVal){ if(root == null){ return length; } // 判断当前是否连续 int currLen = preVal + 1 == root.val ? length + 1 : 1; // 返回当前长度,左子树长度,和右子树长度中较大的那个 return Math.max(currLen, Math.max(findLongest(root.left, currLen, root.val), findLongest(root.right, currLen, root.val))); }}
阅读全文
0 0
- JavaShowAlgorithm-Binary Tree Longest Consecutive Sequence
- Binary Tree Longest Consecutive Sequence
- Binary Tree Longest Consecutive Sequence
- Binary Tree Longest Consecutive Sequence
- Binary Tree Longest Consecutive Sequence
- Binary Tree Longest Consecutive Sequence
- Binary Tree Longest Consecutive Sequence
- leetcode 298: Binary Tree Longest Consecutive Sequence
- Leetcode: Binary Tree Longest Consecutive Sequence
- [LeetCode298]Binary Tree Longest Consecutive Sequence
- 298. Binary Tree Longest Consecutive Sequence
- Leetcode 298Binary Tree Longest Consecutive Sequence
- [Leetcode]Binary Tree Longest Consecutive Sequence
- LeetCode 298. Binary Tree Longest Consecutive Sequence
- Leetcode Binary Tree Longest Consecutive Sequence
- LeetCode 298. Binary Tree Longest Consecutive Sequence
- LintCode Binary Tree Longest Consecutive Sequence II
- 298. Binary Tree Longest Consecutive Sequence
- 面向对象---多态
- 程序猿的日常——SpringMVC系统架构与流程回顾
- Maven之新建web项目后目录不全与jsp报错-yellowcong
- html head标签结构说明
- py-faster-rcnn demo.py分析(py-faster-rcnn)
- JavaShowAlgorithm-Binary Tree Longest Consecutive Sequence
- C#中的相等
- 烧脑的经典科幻电影—— 《The Matrix》
- 解决问题python
- T
- python面向对象-类
- 数据库不适合Docker及容器化的7大原因
- 数据结果第八周项目4--稀疏矩阵的三元组表示的实现及应用
- 感恩的深思