这三道题使用同一种套路:递归
PS:涉及到二叉树相关的最值位置,一般都采用DFS。
1. 二叉树直径
概念:一棵二叉树的直径长度是任意两个结点路径长度中的最大值
1.1 解法
遍历每一个节点,以每个节点为中心计算最长路径(左子树路径 + 右子树路径),更新全局最大路径。
class Solution{
int maxDiameter = 0 ;
public int diameterOfBinaryTree(TreeNode root){
if(root == null){
return 0;
}
}
public int dfs(TreeNode root){
if(root.left == null && root.right == null){
return 0;
}
int leftDiameter = (root.left == null ) ? 0 : dfs(root.left) + 1;
int rightDiameter = (root.right == null) ? 0 : dfs(root.right) + 1;
maxDiameter = Math.max(maxDiameter,leftDiameter + rightDiameter);
return Math.max(leftDiameter,rightDiameter);
}
}
2.最长同值路径
给定一个二叉树,找到最长的路径,这个路径中的每个节点具有相同值。 这条路径可以经过也可以不经过根节点。
2.1 解法
class Solution{
int maxPath = 0;
public int longestUnivaluePath(TreeNode root){
if(root == null){
return 0;
}
dfs(root);
return maxPath;
}
public int dfs(TreeNode root){
if(root.left == null && root.right == null){
return 0;
}
int leftPath = (root.left == null) ? 0 : dfs(root.left) + 1;
int rightPath = (root.right == null) ? 0 dfs(root.right) + 1;
/**
* 题目要求每个节点是相同值。故如果当前节点和其左,右子节点的值不同,则将其路径重新赋值0
*/
if(leftPath > 0 && root.left.val != root.val){
leftPath = 0;
}
if(rightPath > 0 && root.right.val != root.val){
rightPath = 0;
}
maxPath = Math.max(maxPath,leftPath + rightPath);
return Math.max(leftPath,rightPath);
}
}
3. 二叉树的最大路径和
路径:一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。同一个节点在一条路径序列中 至多出现一次 。
路径和:路径中各结点值的总和。
题目中求的最大路径和。
3.1 解法
class Solution{
// 这里因为有负数的存在,最大值要设置为最小值。
int max = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root){
dfs(root);
return max;
}
public int dfs(TreeNode root){
if(root == null) return 0;
// 求最大路径和,故舍弃左,右孩子的路径和为负的情况。
int left = Math.max(0,dfs(root.left));
int right = Math.max(0,dfs(root.right));
max = Math.max(max,left + right + root.val);
return Math.max(left,right) + root.val;
}
}