原题网址:https://leetcode.com/problems/binary-tree-longest-consecutive-sequence/
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
,not
3-2-1
, so return
2
.
方法:递归遍历,递归函数传入父节点的值,以帮助子节点判断是否连续。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private int max = 0;
private void find(TreeNode root, int parent, int count) {
if (root.val == parent+1) count ++; else count = 1;
max = Math.max(max, count);
if (root.left != null) find(root.left, root.val, count);
if (root.right != null) find(root.right, root.val, count);
}
public int longestConsecutive(TreeNode root) {
if (root == null) return 0;
max = 1;
if (root.left != null) find(root.left, root.val, 1);
if (root.right != null) find(root.right, root.val, 1);
return max;
}
}
优化:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private int max = 1;
private void find(TreeNode root, int prev, int len) {
if (prev+1 == root.val) len ++; else len = 1;
max = Math.max(max, len);
if (root.left != null) find(root.left, root.val, len);
if (root.right != null) find(root.right, root.val, len);
}
public int longestConsecutive(TreeNode root) {
if (root == null) return 0;
find(root, 0, 0);
return max;
}
}
二叉树最长连续路径

本文介绍了一种解决LeetCode上二叉树最长连续序列路径问题的方法。通过递归遍历二叉树,并利用递归函数传递当前节点值来辅助判断子节点序列是否连续,最终找到最长连续路径。
802

被折叠的 条评论
为什么被折叠?



