二叉树的直径 题目描述
思路
遍历每一个节点,以每一个节点为中心点计算最长路径(左子树边长+右子树边长),更新全局变量max。
代码及注释
class Solution {
int max = 0;
public int diameterOfBinaryTree(TreeNode root) {
if(root == null){
return 0;
}
dfs(root);
return max;
}
public int dfs(TreeNode root){
if(root == null ){
return 0;
}
int leftSize = root.left == null ? 0 : dfs( root.left ) + 1;
int rightSize = root.right == null ? 0 : dfs( root.right ) + 1;
max = Math.max( leftSize + rightSize, max);
return Math.max(leftSize, rightSize); // 这一步太妙了,你偷偷更新max, 我当看不见, 然后我该返回什么,就返回什么
}
}
类似题 最长同值路径 思路
代码及注释
class Solution {
int max = 0;
public int longestUnivaluePath(TreeNode root) {
if(root == null ){
return 0;
}
dfs(root);
return max;
}
public int dfs(TreeNode root){
if(root.left == null && root.right == null){ // 这里是 && ,不能是 ||
return 0;
}
// 这里不对, 不管 root.val 是否等于 root.left.val, 都应该保证递归能够进行下去, 这样才能发现其他满足条件的路径,因为本题不要求必须通过根节点。
// int left = root.left == null || root.val != root.left.val ? 0 :dfs(root.left) + 1;
// int right = root.right == null || root.val != root.right.val ? 0 :dfs(root.right) + 1;
int left = root.left == null ? 0 :dfs(root.left) + 1;
int right = root.right == null ? 0 :dfs(root.right) + 1;
if( root.left != null && root.val != root.left.val){
left = 0;
}
if(root.right != null && root.val != root.right.val){
right = 0;
}
max = Math.max( max, left + right );
return Math.max( left, right );
}
}
相关DFS题,不是很类似 最大路径和 思路![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/89ccefda53b3782a9cfc130541a96431.png)
代码及注释
class Solution {
int maxSum = Integer.MIN_VALUE; // 初始化也有坑。 本题最大路径和有可能是负数,所以maxsum初始不能为0
public int maxPathSum(TreeNode root) {
if(root == null){
return 0;
}
dfs(root);
return maxSum;
}
public int dfs(TreeNode root){
if(root == null){
return 0;
}
/* int leftsum = root.left == null ? 0 : dfs(root.left); // 此处要注意 本题结点的val可能有负值,所以dfs()的结果可能为负,要改成max(0.dfs(root.left))
int rightsum = root.right == null ? 0 : dfs(root.right);*/
int leftsum = Math.max(0, dfs(root.left));
int rightsum = Math.max(0, dfs(root.right));
maxSum = Math.max(maxSum, leftsum + rightsum + root.val); // 第543题,只是求任两点之间最长路径,所以根节点只是一个点,对结果没有贡献,
// 但是本题,试求路径上结点值的和,根节点也有贡献,所以此处要加上 root.val
return Math.max(leftsum,rightsum) + root.val ; // 同理, 根节点有贡献
}
}