use a global variable to keep track of current max length. I think the code is self explaining.

class Solution {

public:

int longestConsecutive(TreeNode* root) {

int count=0;

if(root==NULL) return 0;

lc(root,count);

return count;

}

```
int lc(TreeNode* root,int& count){
int leftCount=0,rightCount=0;
int res=1;
if(root->left) leftCount = lc(root->left,count);
if(root->right) rightCount = lc(root->right,count);
if(root->left && root->val == root->left->val-1) res = max(res,1+leftCount);
if(root->right && root->val == root->right->val-1) res = max(res,1+rightCount);
if(res>count) count = res;
return res;
}
```

};