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:

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

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    int longest = 0;
    public int longestUnivaluePath(TreeNode root) {
        traverse(root);
        return longest;
    }
    public int traverse(TreeNode node){
        if(node==null) return 0;
        int l=traverse(node.left);
        int r=traverse(node.right);
        int left = (node.left!=null && node.left.val==node.val)? l+1:0;
        int right = (node.right!=null && node.right.val==node.val)? r+1:0;
        longest = Math.max(longest,left + right);
        return Math.max(left,right);
    }
}

你可能感兴趣的:(687. Longest Univalue Path)