JIAKAOBO

LeetCode

venmo
wechat

感谢赞助!

  • ㊗️
  • 大家
  • offer
  • 多多!

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:

img

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:

img

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:

  • The number of nodes in the tree is in the range $[0, 10^4]$.
  • -1000 <= Node.val <= 1000
  • The depth of the tree will not exceed 1000.

Code

250. Count Univalue Subtrees

class Solution {
    int res = 0;
    public int longestUnivaluePath(TreeNode root) {
        helper(root);
        return res;
    }

    private int helper(TreeNode root) {
        if(root == null) return 0;

        int left = helper(root.left);
        int right = helper(root.right);

        int leftPath = 0;
        int rightPath = 0;

        if(left != 0 && root.val == root.left.val) {
            leftPath = left;
        }

        if(right != 0 && root.val == root.right.val) {
            rightPath = right;
        }

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

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