Problem:
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.
Explanation:
找出结点值相同的最长路径。
My Thinking:
维护一个公有变量更新最大值。
My Solution:
class Solution {
private int max=0;
public int longestUnivaluePath(TreeNode root) {
recursive(root);
return max;
}
public int recursive(TreeNode root){
if(root==null)
return 0;
int leftsum=recursive(root.left);
int rightsum=recursive(root.right);
int left=0,right=0;
if(root.left!=null && root.left.val==root.val){
left=leftsum+1;
}
if(root.right!=null && root.right.val==root.val){
right=rightsum+1;
}
max=Math.max(max,left+right);
return Math.max(left,right);
}
}
Optimum Thinking:
Optimum Solution: