Same idea

public class Solution { int max = 0; public int longestConsecutive(TreeNode root) { if(root == null) return 0; helper(root,1); return max; } public int helper(TreeNode root, int count){ max = Math.max(max,count); int left = 0,right = 0; if(root.left != null) left = helper(root.left,(root.left.val - root.val == 1)?count+1:1); if(root.right != null) right = helper(root.right,root.right.val - root.val == 1?count+1:1); return Math.max(left,right); } }But after looking yours, I found mine is more stupid... No need to return value in the sub method. Only update the max length within recursive.

Updated:

public class Solution { int max = 0; public int longestConsecutive(TreeNode root) { if(root == null) return 0; helper(root,1); return max; } public void helper(TreeNode root, int count){ max = Math.max(max,count); if(root.left != null) helper(root.left,(root.left.val - root.val == 1)?count+1:1); if(root.right != null) helper(root.right,root.right.val - root.val == 1?count+1:1); } }