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
).
Have you met this question in a real interview? Yes
Problem Correction
Example
Example 1:
Input:
1
\
3
/ \
2 4
\
5
Output:3
Explanation:
Longest consecutive sequence path is 3-4-5, so return 3.
Example 2:
Input:
2
\
3
/
2
/
1
Output:2
Explanation:
Longest consecutive sequence path is 2-3,not 3-2-1, so return 2.
分析
简单的递归就可以计算。
Code
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: the root of binary tree
* @return: the length of the longest consecutive sequence path
*/
int longestConsecutive(TreeNode * root) {
// write your code here
if (!root)
return 0;
int maxLen = 0;
findLongest(root, 1, maxLen);
return maxLen;
}
void findLongest(TreeNode* root, int len, int& maxLen)
{
if (!root)
return;
maxLen = max(maxLen, len);
if (root->left)
{
if (root->val == root->left->val - 1)
findLongest(root->left, len+1, maxLen);
else
findLongest(root->left, 1, maxLen);
}
if (root->right)
{
if (root->val == root->right->val - 1)
findLongest(root->right, len+1, maxLen);
else
findLongest(root->right, 1, maxLen);
}
}
};
运行效率
Your submission beats 76.60% Submissions!