[LeetCode] 298. Binary Tree Longest Consecutive Sequence

Given a binary tree, find the length of the longest consecutive sequence path.
The path refers to any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The longest consecutive path need to be from parent to child (cannot be the reverse).
For example,
   1
    \
     3
    / \
   2   4
        \
         5
Longest consecutive sequence path is 3-4-5, so return 3.
   2
    \
     3
    / 
   2    
  / 
 1
Longest consecutive sequence path is 2-3,not3-2-1, so return 2.

Thought process:
Recursion. Use an instance variable to keep track of longest path.
  • Base case:
    • Node == null: update longest and return.
    • Node.val != parent.val + 1: update longest and reset current path length.

Solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private int longest = 0;
    
    public int longestConsecutive(TreeNode root) {
        longestConsecutive(root, null, 0);
        return longest;
    }
    
    private void longestConsecutive(TreeNode node, TreeNode parent, int current) {
        if (node == null) {
            longest = Math.max(longest, current);
            return;
        }
        if (parent != null && node.val != parent.val + 1) {
            longest = Math.max(longest, current);
            current = 0;
        }
        
        longestConsecutive(node.left, node, current + 1);
        longestConsecutive(node.right, node, current + 1);
    }
}

Time complexity: O(n).

Comments

Popular posts from this blog

[LeetCode] 269. Alien Dictionary

[HackerRank] Roads and Libraries

[LeetCode] 631. Design Excel Sum Formula