Leetcode 687. Longest Univalue Path
题目链接: Longest Univalue Path
难度:Medium
题目大意:
详见题目。
思路:
本题思路与Leetcode543类似,只是增加了路径上所有节点的值要相同这一条件。
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int max=Integer.MIN_VALUE;
public int longestUnivaluePath(TreeNode root) {
if(root==null){
return 0;
}
longestPathDown(root);
return max;
}
public int longestPathDown(TreeNode root){//从上而下的最长路径
if(root==null){
return 0;
}
int left=0,right=0;
left=longestPathDown(root.left);
right=longestPathDown(root.right);
if(root.left==null||root.left.val!=root.val){
left=0;
}
if(root.right==null||root.right.val!=root.val){
right=0;
}
max=Math.max(max,left+right);
return Math.max(left,right)+1;
}
}