题目:
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.
解析:
求二叉树的最长连续序列的长度,要从父节点到子节点。最长连续子序列必须是从root到leaf的方向。 比如 1->2,返回长度2, 比如1->3->4->5,返回3->4->5这个子序列的长度3。
解法:递归遍历binary tree,递归函数传入父节点的值,以帮助子节点判断是否连续。
public class Solution {
private int maxLen = 0;
// 递归解
public int longestConsecutive(TreeNode root) {
longestConsecutive(root, 0, 0);
return maxLen;
}
// 递归
private void longestPath(TreeNode root, int rooterVal, int curLen){
if(root == null) return ;
// 如果不相等,curLen设为计算起点, 即1
if(root.val != rooterVal + 1) curLen = 1;
else
// 否则继续往下遍历,并且长度+1
curLen++;
// 取最大长度
maxLen = Math.max(maxLen, curLen);
// 递归左右节点
longestPath(root.left, root.val, curLen);
longestPath(root.right, root.val, curLen);
}
}