【每日一题-leetcode】124. 二叉树中的最大路径和

124. 二叉树中的最大路径和

  1. 二叉树中的最大路径和

难度困难595

给定一个非空二叉树,返回其最大路径和。

本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。

示例 1:

输入: [1,2,3]

       1
      / \
     2   3

输出: 6
private int res = Integer.MIN_VALUE;

public int maxPathSum(TreeNode root) {
     
    if(root == null){
     
        return res;
    }
    dfs(root);
    return res;
}

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));
    //将最大值存储到res中
    res = Math.max(res,root.val+left+right);
    //返回当前最大的子树和+root.val
    return root.val+Math.max(left,right);
}

你可能感兴趣的:(#,leetcode,#,二叉树,#,深度优先搜索)