KatInterview

687. Longest Univalue Path

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 path in a binary tree where every node on the path has the same value. The length is defined as the number of edges. This path does not necessarily have to pass through the root of the tree.

Solution

Longest Univalue Path 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 longestUnivaluePath(self, root: Optional[TreeNode]) -> int:
        # Use an instance variable to store the maximum length found so far.
        self.maxLength = 0

        def dfs(node: Optional[TreeNode]) -> int:
            """
            Performs DFS. Returns the length of the longest univalue path starting from 'node' 
            and going downwards. It also updates the global self.maxLength.
            """
            # Base case: if the node is null, the path length is 0.
            if not node:
                return 0

            # Recursively find the longest univalue path starting from left and right children.
            left_path = dfs(node.left)
            right_path = dfs(node.right)

            # Calculate the length of the path going downwards from the current node.
            arrow_left = 0
            arrow_right = 0

            # If left child exists and has the same value, extend the path.
            if node.left and node.left.val == node.val:
                arrow_left = 1 + left_path
            
            # If right child exists and has the same value, extend the path.
            if node.right and node.right.val == node.val:
                arrow_right = 1 + right_path
            
            # Update the global maximum length.
            # This considers the path that might "turn" or be centered at the current node.
            self.maxLength = max(self.maxLength, arrow_left + arrow_right)

            # Return the longest univalue path that starts at 'node' and goes down one side.
            # The parent of 'node' can only extend one of these paths.
            return max(arrow_left, arrow_right)

        dfs(root)
        return self.maxLength

Longest Univalue Path 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 longestUnivaluePath(TreeNode root) {
        dfs(root);
        return maxLength;
    }

    // Helper function to perform DFS.
    // Returns the length of the longest univalue path starting from 'node' and going downwards.
    // It also updates the global maxLength.
    private int dfs(TreeNode node) {
        // Base case: if the node is null, the path length is 0.
        if (node == null) {
            return 0;
        }

        // Recursively find the longest univalue path starting from left and right children.
        int leftPath = dfs(node.left);
        int rightPath = dfs(node.right);

        // Calculate the length of the path going downwards from the current node.
        int arrowLeft = 0;
        int arrowRight = 0;

        // If left child exists and has the same value, extend the path.
        if (node.left != null && node.left.val == node.val) {
            arrowLeft = 1 + leftPath;
        }

        // If right child exists and has the same value, extend the path.
        if (node.right != null && node.right.val == node.val) {
            arrowRight = 1 + rightPath;
        }

        // Update the global maximum length.
        // This considers the path that might "turn" or be centered at the current node.
        maxLength = Math.max(maxLength, arrowLeft + arrowRight);

        // Return the longest univalue path that starts at 'node' and goes down one side.
        // The parent of 'node' can only extend one of these paths.
        return Math.max(arrowLeft, arrowRight);
    }
}

Longest Univalue Path 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.
    // Returns the length of the longest univalue path starting from 'node' and going downwards.
    // It also updates the global maxLength.
    int dfs(TreeNode* node) {
        // Base case: if the node is null, the path length is 0.
        if (!node) {
            return 0;
        }

        // Recursively find the longest univalue path starting from left and right children.
        int leftPath = dfs(node->left);
        int rightPath = dfs(node->right);

        // Calculate the length of the path going downwards from the current node.
        int arrowLeft = 0;
        int arrowRight = 0;

        // If left child exists and has the same value, extend the path.
        if (node->left && node->left->val == node->val) {
            arrowLeft = 1 + leftPath;
        }

        // If right child exists and has the same value, extend the path.
        if (node->right && node->right->val == node->val) {
            arrowRight = 1 + rightPath;
        }

        // Update the global maximum length. 
        // This considers the path that might "turn" or be centered at the current node.
        maxLength = std::max(maxLength, arrowLeft + arrowRight);

        // Return the longest univalue path that starts at 'node' and goes down one side.
        // The parent of 'node' can only extend one of these paths.
        return std::max(arrowLeft, arrowRight);
    }

public:
    int longestUnivaluePath(TreeNode* root) {
        dfs(root);
        return maxLength;
    }
};

Longest Univalue Path 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 longestUnivaluePath(root: TreeNode | null): number {
    let maxLength = 0;

    /**
     * Helper function to perform DFS.
     * Returns the length of the longest univalue path starting from 'node' and going downwards.
     * It also updates the closure variable maxLength.
     */
    function dfs(node: TreeNode | null): number {
        // Base case: if the node is null, the path length is 0.
        if (!node) {
            return 0;
        }

        // Recursively find the longest univalue path starting from left and right children.
        const leftPath = dfs(node.left);
        const rightPath = dfs(node.right);

        // Calculate the length of the path going downwards from the current node.
        let arrowLeft = 0;
        let arrowRight = 0;

        // If left child exists and has the same value, extend the path.
        if (node.left && node.left.val === node.val) {
            arrowLeft = 1 + leftPath;
        }

        // If right child exists and has the same value, extend the path.
        if (node.right && node.right.val === node.val) {
            arrowRight = 1 + rightPath;
        }

        // Update the maximum length found so far.
        // This considers the path that might "turn" or be centered at the current node.
        maxLength = Math.max(maxLength, arrowLeft + arrowRight);

        // Return the longest univalue path that starts at 'node' and goes down one side.
        // The parent of 'node' can only extend one of these paths.
        return Math.max(arrowLeft, arrowRight);
    }

    dfs(root);
    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.