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).
using recursive is easier.
public class Solution {
int max = 0;
public:
int longestConsecutive(TreeNode* root) {
if(!root) return 0;
helper(root,0,root.val);
return max;
}
private:
void helper(TreeNode* root,int cur, int target){
if(root) return;
if(root->val==target) cur++;
else cur=1;
max = max(cur, max);
helper(root->left, cur, root->val+1);
helper(root->right, cur, root->val+1);
}
}