- Binary Tree Longest Consecutive Sequence
中文English
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).
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.
解法1:
递归
代码如下:
/**
* 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) {
helper(root);
return maxLen;
}
private:
int maxLen = 0;
int helper(TreeNode * root) {
if (!root) return 0;
if (!root->left && !root->right) return 1;
int leftNum = 0, rightNum = 0;
if (root->left) {
leftNum = helper(root->left);
if (root->val == root->left->val - 1) {
leftNum++;
maxLen = max(maxLen, leftNum);
} else {
maxLen = max(maxLen, leftNum);
leftNum = 1;
}
}
if (root->right) {
rightNum = helper(root->right);
if (root->val == root->right->val - 1) {
rightNum++;
maxLen = max(maxLen, rightNum);
} else {
maxLen = max(maxLen, rightNum);
rightNum = 1;
}
}
return max(leftNum, rightNum);
}
};
二刷:
class Solution {
public:
/**
* @param root: the root of binary tree
* @return: the length of the longest consecutive sequence path
*/
int longestConsecutive(TreeNode *root) {
if (!root) return 0;
helper(root, 1);
return gMaxPathLen;
}
private:
int gMaxPathLen = 0;
void helper(TreeNode *root, int pathLen) {
if (!root) return;
gMaxPathLen = max(gMaxPathLen, pathLen);
if (root->left && root->val + 1 == root->left->val) helper(root->left, pathLen + 1);
else helper(root->left, 1);
if (root->right && root->val + 1 == root->right->val) helper(root->right, pathLen + 1);
else helper(root->right, 1);
return;
}
};
博客围绕二叉树最长连续序列问题展开,给定二叉树,需找出从父节点到子节点的最长连续序列路径长度。文中给出两个示例说明问题,并提及使用递归方法解决该问题。
391

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



