二叉树的直径和二叉树中的最大路径和

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35508033/article/details/88934057

二叉树的直径

https://leetcode-cn.com/problems/diameter-of-binary-tree/

先用求树高的方式求出了根节点的左右子树高度,加起来便是

采用分治和递归的思想:根节点为root的二叉树的直径 = Max(左子树直径,右子树直径,左子树的最大深度(不包括根节点)+右子树的最大深度(不包括根节点)+1)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int max=0;
    public int diameterOfBinaryTree(TreeNode root) {
        maxDistance(root);
        return max;
    }
    private int maxDistance(TreeNode root){
        if(root==null){
            return 0;
        }
        int l=maxDistance(root.left);
        int r=maxDistance(root.right);
        max=Math.max(max,l+r);
        return Math.max(l,r)+1;
    }
}

二叉树中的最大路径和

https://leetcode-cn.com/problems/binary-tree-maximum-path-sum/

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int maxVal=Integer.MIN_VALUE;
    public int maxPathSum(TreeNode root) {
        maxCore(root);
        return maxVal;
    }
    private int maxCore(TreeNode root){
        if(root==null){
            return 0;
        }
        // 求以root为根的当前子树的最大路径和
		// 如果左右子树都是负数
		// 那么就最大路径就是当前结点值(无论正负)
        int curVal=root.val;// 使用curValue,来标记左+右+root
        int lmax=maxCore(root.left);
        int rmax=maxCore(root.right);
        if(lmax>0){
            curVal+=lmax;
        }
        if(rmax>0){
            curVal+=rmax;
        }
        maxVal=Math.max(maxVal,curVal);
        // 返回以当前root为根的子树的最大路径和
		// 左右有可能都为负数,所以需要参与比较大小
        int thisMax=Math.max(lmax+root.val,Math.max(rmax+root.val,root.val));
        return thisMax;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_35508033/article/details/88934057