Binary Tree Longest Consecutive Sequence
Problem Descriptionβ
Visit LeetCode for the full problem description.
Solutionsβ
Solution 1: C# (Best: 136 ms)β
| Metric | Value |
|---|---|
| Runtime | 136 ms |
| Memory | 32.5 MB |
| Date | 2019-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β
| Approach | Time | Space |
|---|---|---|
| Solution | To be analyzed | To be analyzed |