leetcode--Binary Tree Maximum Path Sum

Given a binary tree, find the maximum path sum.

The path may start and end at any node in the tree.

For example:
Given the below binary tree,

       1
      / \
     2   3

Return 6.


题意:对于给定二叉树,查找最长路径和。该路径的起点,终点可以是二叉树的任意一个节点。

分类:二叉树


解法1:以采用Binary Tree最常用的dfs来进行遍历。先算出左右子树的结果L和R,如果L大于0,那么对后续结果是有利的,我们加上L,如果R大于0,对后续结果也是有利的,继续加上R。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int maxPathSum(TreeNode root) {
        max = Integer.MIN_VALUE;
        dfs(root);
        return max;
    }
    
    int max = 0;//最大值
    /**
     * 该方法返回包含t节点的最大路径和 
     */
    int dfs(TreeNode t){
        if(t==null) return 0;//如果为空,路径和为0
        int left = dfs(t.left);//包含左节点的最大路径和left
        int right = dfs(t.right);//包含右节点的最大路径和right
        int curmax = t.val;//当前节点,当前和
        if(left>0) curmax += left;//如果左节点不为0,加上
        if(right>0) curmax += right;//如果右节点不为0,也加上
        max = Math.max(max,curmax);//与当前最大值比较,更新
        if(left>0||right>0){//如果左节点或者右节点,大于0
            return left>right?left+t.val:right+t.val;
        }else{//如果左右节点都是负数或者0,返回当前节点值即可
            return t.val;
        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值