Posts Binary Tree Longest Consecutive Sequence
Post
Cancel

Binary Tree Longest Consecutive Sequence

PROBLEM DESCRIPTION

Given the root of a binary tree, return the length of the longest consecutive sequence path. A consecutive sequence path is a path where the values increase by one along the path. Note that the path can start at any node in the tree, and you cannot go from a node to its parent in the path.

leetcode

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {

    int maxLength;  // Initialize a variable to store the maximum length of consecutive sequence path.

    public int longestConsecutive(TreeNode root) {
        dfs(root);  // Start the DFS traversal from the root node.
        return maxLength;  // Return the calculated maximum length.
    }

    public void dfs(TreeNode root) {
        if (root == null) return;  // If the current node is null, return (base case for recursion).

        longestConsecutive(root.left);  // Recursively traverse the left subtree.
        helper(root);  // Call the helper function to calculate the consecutive sequence length.
        longestConsecutive(root.right);  // Recursively traverse the right subtree.
    }

    public int helper(TreeNode root) {
        if (root == null) return 0;  // If the current node is null, return 0 (base case for recursion).

        int left = 1;  // Initialize a variable to store the length of consecutive sequence in the left subtree.
        int right = 1;  // Initialize a variable to store the length of consecutive sequence in the right subtree.

        // Check if there is a consecutive sequence in the left subtree.
        if (root.left != null && root.left.val == root.val + 1) {
            left = 1 + helper(root.left);  // Update the left length and recursively explore the left subtree.
        }

        // Check if there is a consecutive sequence in the right subtree.
        if (root.right != null && root.right.val == root.val + 1) {
            right = 1 + helper(root.right);  // Update the right length and recursively explore the right subtree.
        }

        int currentLength = Math.max(left, right);  // Calculate the current consecutive sequence length.
        maxLength = Math.max(maxLength, currentLength);  // Update the maximum length if necessary.

        return currentLength;  // Return the current consecutive sequence length.
    }
}
This post is licensed under CC BY 4.0 by the author.