614 · Binary Tree Longest Consecutive Sequence II
Algorithms
Medium
Description
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
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
Tags
Company
Google
Related Problems
472
Binary Tree Path Sum III
Hard
595
Binary Tree Longest Consecutive Sequence
Easy
619
Binary Tree Longest Consecutive Sequence III
Medium
717
Tree Longest Path With Same Value
Medium
解法1:后序遍历。helper()返回当前节点的incrLen 和 decrLen,同时维护当前最大的maxLen = max(maxLen, incrLen + decrLen - 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 longestConsecutive2