```
public class Solution {
public int longestConsecutive(TreeNode root) {
int[] max = new int[]{0};
longestConsecutive(root, max);
return max[0];
}
private int longestConsecutive(TreeNode node, int[] max) {
if (node == null) {
return 0;
}
int res = 1;
int left = longestConsecutive(node.left, max);
int right = longestConsecutive(node.right, max);
if (node.left == null || node.val + 1 != node.left.val) {
left = 0;
}
if (node.right == null || node.val + 1 != node.right.val) {
right = 0;
}
res += Math.max(right, left);
max[0] = Math.max(res, max[0]);
return res;
}
}
```