yokostan / Leetcode-Solutions

Doing exercise on Leetcode. Carry on!
0 stars 3 forks source link

Leetcode #298. Binary Tree Longest Consecutive Sequence #251

Open yokostan opened 5 years ago

yokostan commented 5 years ago
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int max = 0;
    public int longestConsecutive(TreeNode root) {
        if (root == null) return 0;
        helper(root, 0, root.val);
        return max;
    }

    public void helper(TreeNode root, int curr, int target) {
        if (root == null) return ;
        if (root.val == target) curr++;
        else curr = 1;
        max = Math.max(curr, max);
        helper(root.left, curr, root.val + 1);
        helper(root.right, curr, root.val + 1);
    }
}