LeetCode 687: Longest Univalue Path Solution

Master LeetCode problem 687 (Longest Univalue Path), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

687. Longest Univalue Path

Problem Explanation

Explanation

To solve this problem, we can perform a depth-first search (DFS) on the binary tree. At each node, we need to calculate the length of the longest path that can be formed by extending the current node's value either left or right. We keep track of the longest path found so far and update it if necessary.

We define a helper function that calculates the longest path starting from a given node and extending in one direction. This function returns the length of the path. Then, in the main function, we recursively call this helper function for each node in the tree to find the maximum path length.

Time complexity: O(n) - where n is the number of nodes in the binary tree Space complexity: O(h) - where h is the height of the binary tree

Solution Code

class Solution {
    int maxPath = 0;

    public int longestUnivaluePath(TreeNode root) {
        if (root == null) {
            return 0;
        }
        dfs(root);
        return maxPath;
    }

    private int dfs(TreeNode node) {
        if (node == null) {
            return 0;
        }

        int left = dfs(node.left);
        int right = dfs(node.right);

        int leftPath = (node.left != null && node.left.val == node.val) ? left + 1 : 0;
        int rightPath = (node.right != null && node.right.val == node.val) ? right + 1 : 0;

        maxPath = Math.max(maxPath, leftPath + rightPath);

        return Math.max(leftPath, rightPath);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 687 (Longest Univalue Path)?

This page provides optimized solutions for LeetCode problem 687 (Longest Univalue Path) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 687 (Longest Univalue Path)?

The time complexity for LeetCode 687 (Longest Univalue Path) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 687 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 687 in Java, C++, or Python.

Back to LeetCode Solutions