Binary Tree Longest Consecutive Sequence
Thoughts
Code
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private int helper(TreeNode root, int count, int val) {
if (root == null) {
return count;
}
count = (root.val - val) == 1 ? count + 1 : 1;
int left = helper(root.left, count, root.val);
int right = helper(root.right, count, root.val);
return Math.max(Math.max(left, right), count);
}
public int longestConsecutive(TreeNode root) {
return helper(root, 0, root == null ? 0 : root.val);
}
}Analysis
Last updated