您的位置:首页 > 产品设计 > UI/UE

Binary Tree Longest Consecutive Sequence -- LeetCode

2016-08-31 08:07 405 查看
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
,not
3-2-1
, so return
2
.

思路:递归。时间复杂度O(N)。

/**
* 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 help(TreeNode *root, int &count) {
if (root == NULL) return 0;
int leftCount = help(root->left, count);
int rightCount = help(root->right, count);
int res = 1;
if (root->left && root->val + 1 == root->left->val)
res = 1 + leftCount;
if (root->right && root->val + 1 == root->right->val)
res = std::max(res, 1 + rightCount);
count = std::max(count, res);
return res;
}
int longestConsecutive(TreeNode* root) {
int count = 0;
help(root, count);
return count;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: