版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ghscarecrow/article/details/86555696
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: The given binary tree has not more than 10000 nodes. The height of the tree is not more than 1000.
思考:一道天然的递归题目,可以采用自底向上递归的方法,思考几个问题:如何设置递归子式?返回什么值?如何判断什么时候可以对当前返回的路径值加一?
我们易知一棵树的最长相同值路径至少为其左右子树的最长相同值路径的最大值,当当前根结点的值与取得最长相同值路径的子树根结点的值相同时,那么可以使当前最长相同跟路径加一。
即:树最长相同值路径 = Max{左子树最长相同值结点路径,右子树最长相同值结点路径} + 1 or +0;
返回值为当前树的最长相同值路径长度,即max{左子树最长相同值结点路径,右子树最长相同值结点路径};
实现代码如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int ans;
public int longestUnivaluePath(TreeNode root) {
ans = 0;
dfs(root);
return ans;
}
public int dfs(TreeNode node){
if(node==null){
return 0;
} else {
int left = dfs(node.left);
int right = dfs(node.right);
int arrowLeft=0,arrowRight=0;
if(node.left != null && node.left.val==node.val){
arrowLeft = left + 1;
}
if(node.right != null && node.right.val==node.val){
arrowRight = right + 1;
}
ans = Math.max(ans,arrowLeft + arrowRight);
return Math.max(arrowLeft,arrowRight);
}
}
}