KatInterview

298. Binary Tree Longest Consecutive Sequence

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the length of the longest consecutive sequence path in a binary tree. A path is consecutive if each node's value is one greater than its parent's value. The path can start at any node and must go downwards (from parent to child).

Solution

Binary Tree Longest Consecutive Sequence in Python

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def longestConsecutive(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        
        self.max_length = 0
        # Start DFS from the root. For the root, there is no parent,
        # and the length of the sequence ending at the parent is 0.
        self.dfs(root, None, 0)
        return self.max_length

    def dfs(self, node: Optional[TreeNode], parent: Optional[TreeNode], parent_length: int):
        if not node:
            return

        # Calculate the length of the consecutive sequence ending at the current node
        if parent and node.val == parent.val + 1:
            current_length = parent_length + 1
        else:
            current_length = 1
        
        # Update the global maximum length found so far
        self.max_length = max(self.max_length, current_length)

        # Recurse for the left and right children
        # The current node becomes the parent, and current_length becomes the parent_length for the children
        self.dfs(node.left, node, current_length)
        self.dfs(node.right, node, current_length)

Binary Tree Longest Consecutive Sequence in Java

/**
 * 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 {
    private int maxLength = 0;

    public int longestConsecutive(TreeNode root) {
        if (root == null) {
            return 0;
        }
        // Start DFS from the root. For the root, there's no parent, and the path length from parent is 0.
        dfs(root, null, 0);
        return this.maxLength;
    }

    private void dfs(TreeNode node, TreeNode parent, int parentLength) {
        if (node == null) {
            return;
        }

        // Calculate the length of the consecutive sequence ending at the current node
        int currentLength = (parent != null && node.val == parent.val + 1) ? parentLength + 1 : 1;
        
        // Update the global maximum length
        this.maxLength = Math.max(this.maxLength, currentLength);

        // Recurse for the left and right children
        // The current node becomes the parent, and currentLength becomes the parentLength for the children
        dfs(node.left, node, currentLength);
        dfs(node.right, node, currentLength);
    }
}

Binary Tree Longest Consecutive Sequence in C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
private:
    int maxLength = 0;

    // Helper function to perform DFS traversal
    void dfs(TreeNode* node, TreeNode* parent, int parentLength) {
        if (!node) {
            return;
        }

        // Calculate the length of the consecutive sequence ending at the current node
        int currentLength = (parent && node->val == parent->val + 1) ? parentLength + 1 : 1;
        
        // Update the global maximum length
        maxLength = std::max(maxLength, currentLength);

        // Recurse for the left and right children
        // The current node becomes the parent, and currentLength becomes the parentLength for the children
        dfs(node->left, node, currentLength);
        dfs(node->right, node, currentLength);
    }

public:
    int longestConsecutive(TreeNode* root) {
        if (!root) {
            return 0;
        }
        
        // Start DFS from the root. For the root, there's no parent, and the path length from parent is 0.
        dfs(root, nullptr, 0);
        
        return maxLength;
    }
};

Binary Tree Longest Consecutive Sequence in TypeScript

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function longestConsecutive(root: TreeNode | null): number {
    if (!root) {
        return 0;
    }

    let maxLength = 0;

    // Helper function to perform DFS traversal
    function dfs(node: TreeNode | null, parent: TreeNode | null, parentLength: number) {
        if (!node) {
            return;
        }

        // Calculate the length of the consecutive sequence ending at the current node
        const currentLength = (parent && node.val === parent.val + 1) ? parentLength + 1 : 1;
        
        // Update the maximum length found so far. The closure allows updating the outer `maxLength`.
        maxLength = Math.max(maxLength, currentLength);
        
        // Recurse for the left and right children
        // The current node becomes the parent, and currentLength becomes the parentLength for the children
        dfs(node.left, node, currentLength);
        dfs(node.right, node, currentLength);
    }
    
    // Start DFS from the root. For the root, there's no parent, and the path length from parent is 0.
    dfs(root, null, 0);
    
    return maxLength;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.