687. Longest Univalue Path

Given a binary tree, find 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.

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

Example 1:

Input:

              5
             / \
            4   5
           / \   \
          1   1   5

Output:

2

Example 2:

Input:

              1
             / \
            4   5
           / \   \
          4   4   5

Output:

2

Note: The given binary tree has not more than 10000 nodes. The height of the tree is not more than 1000.

Solution

(1) Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int longestUnivaluePath(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int[] max = new int[] {0};
        helper(root, max);
        return max[0];
    }

    private int helper(TreeNode root, int[] max) {
        if (root == null || (root.left == null && root.right == null)) {
            return 0;
        }
        int len = 0;
        int rstLen = 0;
        int ll = helper(root.left, max);
        int rl = helper(root.right, max);
        if (root.left != null && root.right != null && root.val == root.left.val && root.val == root.right.val) {
            len = ll + rl + 2;
            rstLen = Math.max(ll, rl)+1;
        } else if (root.left != null && root.val == root.left.val) {
            len = ll + 1;
            rstLen = Math.max(rstLen, len);
        } else if (root.right != null && root.val == root.right.val) {
            len = rl + 1;
            rstLen = Math.max(rstLen, len);
        } else {
            len = Math.max(ll, rl);
        }
        max[0] = Math.max(max[0], len);
        return rstLen;
    }
}

(2) Python



(3) Scala



results matching ""

    No results matching ""