Skip to main content

Binary Tree Longest Consecutive Sequence

LeetCode Link

Problem Description​

Visit LeetCode for the full problem description.


Solutions​

Solution 1: C# (Best: 136 ms)​

MetricValue
Runtime136 ms
Memory32.5 MB
Date2019-02-18
Solution
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int LongestConsecutive(TreeNode root)
{
if(root == null) return 0;
return helper(root, 0, root.val);

}

public 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);

}



}

Complexity Analysis​

ApproachTimeSpace
SolutionTo be analyzedTo be analyzed