687. Longest Univalue Path

Difficulty:
Related Topics:
Similar Questions:

Problem

Given the root of a binary tree, return the length of the longest path, where each node in the path has the same value. This path may or may not pass through the root.

The length of the path between two nodes is represented by the number of edges between them.

  Example 1:

Input: root = [5,4,5,1,1,null,5]
Output: 2
Explanation: The shown image shows that the longest path of the same value (i.e. 5).

Example 2:

Input: root = [1,4,5,4,4,null,5]
Output: 2
Explanation: The shown image shows that the longest path of the same value (i.e. 4).

  Constraints:

Solution (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 {
    public int longestUnivaluePath(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int[] res = new int[1];
        preorderLongestSinglePathLen(root, res);
        return res[0];
    }

    private int preorderLongestSinglePathLen(TreeNode root, int[] res) {
        if (root == null) {
            return -1;
        }
        int left = preorderLongestSinglePathLen(root.left, res);
        int right = preorderLongestSinglePathLen(root.right, res);

        if (root.left == null || root.val == root.left.val) {
            left = left + 1;
        } else {
            left = 0;
        }

        if (root.right == null || root.val == root.right.val) {
            right = right + 1;
        } else {
            right = 0;
        }
        int longestPathLenPassingThroughRoot = left + right;
        res[0] = Math.max(res[0], longestPathLenPassingThroughRoot);
        return Math.max(left, right);
    }
}

Explain:

nope.

Complexity: