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.
Thoughts
这道题和Diameter of Binary Tree很像,分为两种大情况: maxLen已经在左右树和该结点与左右结点的path形成新的maxPath。因此我们需要记录对应的两个值。
Code
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int len = 0; // global variable
public int longestUnivaluePath(TreeNode root) {
if (root == null) return 0;
len = 0;
getLen(root, root.val);
return len;
}
private int getLen(TreeNode node, int val) {
if (node == null) return 0;
int left = getLen(node.left, node.val);
int right = getLen(node.right, node.val);
len = Math.max(len, left + right);
if (val == node.val) return Math.max(left, right) + 1;
return 0;
}
}