Description
中文English
Given a binary tree, find the length(number of nodes) of the longest consecutive sequence(Monotonic and adjacent node values differ by 1) path.
The path could be start and end at any node in the tree
Have you met this question in a real interview? Yes
Problem Correction
Example
Example 1:
Input:
{1,2,0,3}
Output:
4
Explanation:
1
/ \
2 0
/
3
0-1-2-3
Example 2:
Input:
{3,2,2}
Output:
2
Explanation:
3
/ \
2 2
2-3
分析
要求二叉树中最长的连续数字的长度。可以分别求每个node的递增子树的长度addLen和递减子树的长度decLen。更新最大长度(addLen+decLen + 1),然后返回pair<int,int>。
这道题很难写,之前没想用pair<int, int>表示递增和递减子树的长度,导致很容易超时。
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 maxLen = 0;
int longestConsecutive2(TreeNode * root) {
// write your code here
if (!root)
return 0;
findLong(root);
return maxLen;
}
pair<int, int> findLong(TreeNode* root)
{
if (!root)
return make_pair(0, 0);
pair<int, int> left = findLong(root->left);
pair<int, int> right = findLong(root->right);
int addLen = 0;
int decLen = 0;
if (root->left)
{
if (root->left->val == root->val + 1)
{
addLen = max(addLen, left.first);
}
else if (root->left->val == root->val -1)
{
decLen = max(decLen, left.second);
}
}
if (root->right)
{
if (root->right->val == root->val + 1)
{
addLen = max(addLen, right.first);
}
else if (root->right->val == root->val -1)
{
decLen = max(decLen, right.second);
}
}
maxLen = max(maxLen, addLen + decLen + 1);
return make_pair(addLen+1, decLen+1);
}
};
运行效率
Your submission beats 82.80% Submissions!