Question:
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
.
分析:
可以从递归角度考虑问题,
如果根节点为NULL,直接返回结果为0;
如果根节点不为空,但没有左右节点,说明连续数列只有1个;
如果有左孩子或是右孩子,判断当前节点的值是不是与父节点的值是不是连续的,如果是则将当前len值+1,如果不是,说明可以与父节点断开,len的长度重新赋值为1;
len表示从根节点开始到当前节点为止最大的连续数列长度,以此len值为基础,分别求解当前节点的左右子树连续数列的最大长度。
最后可以知道,到当前节点为止的最大连续数列长度为len、以len为基础的左右子树连续序列长度三者的最大值。
代码如下:
<span style="font-size:14px;">/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int longestConsecutive(TreeNode* root) {
return longest(root, NULL, 0);
}
private:
int longest(TreeNode* now, TreeNode* parent, int len) {
if (!now) return len;
len = (parent && now->val == parent->val + 1) ? len + 1 : 1;
return max(len, max(longest(now->left, now, len), longest(now->right, now, len)));
}
};</span>