计算本节点为起点的价值(路径和/节点数),进而计算遍历”经过本节点的价值“
力扣124. 二叉树中的最大路径和
/**
* 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 {
//注意一条路径,属于遍历所有经过各种root节点的路径
int maxPathSum=Integer.MIN_VALUE;//防止叶子结点小于0
public int maxPathSum(TreeNode root) {
nodeGain(root);
return maxPathSum;
}
//获取每个节点的“最大”贡献值=本节点的值+左右孩子的较大的“非零”贡献值(如果孩子都是负值,就是本身的值)
public int nodeGain(TreeNode root){
if(root==null){
return 0;
}
int left_gain=Math.max(nodeGain(root.left),0);
int right_gain=Math.max(nodeGain(root.right),0);
int temp=root.val+left_gain+right_gain;
maxPathSum=Math.max(temp,maxPathSum);//相当于遍历所有经过root节点的最优路径的情况
return root.val+Math.max(left_gain,right_gain);
}
}
力扣543. 二叉树的直径
/**
* 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 ans=0;
public int diameterOfBinaryTree(TreeNode root) {
node_count(root);
return ans;
}
//计算以每个节点为起点的路径的最多的节点数
public int node_count(TreeNode cur){
if(cur==null){
return 0;
}
int left_count=node_count(cur.left);
int right_count=node_count(cur.right);
//经过本节点的路径的边数==左节点路径的节点个数+右节点路径的节点个数
ans=Math.max(ans,left_count+right_count);
return Math.max(left_count,right_count)+1;
}
}