首页 > 其他 > 详细

【Leetcode】Binary Tree Maximum Path Sum

时间:2016-06-10 11:06:39      阅读:196      评论:0      收藏:0      [点我收藏+]

题目链接:https://leetcode.com/problems/binary-tree-maximum-path-sum/

题目:
Given a binary tree, find the maximum path sum.

For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path does not need to go through the root.

For example:
Given the below binary tree,

   1
  /  2   3

Return 6.

思路:
dfs递归,判断是否选择左右最大的分支,或者选择root结点。。

算法:

    int max = Integer.MIN_VALUE;

    public int maxPathSum(TreeNode root) {
        dsp(root);
        return max;
    }

    public int dsp(TreeNode root) {
        if (root == null)
            return 0;
        int leftMax = dsp(root.left);// 左子树能返回的最大值
        int rightMax = dsp(root.right);
        max = Math.max(
                Math.max(Math.max(
                        Math.max(leftMax + rightMax + root.val, rightMax
                                + root.val), leftMax + root.val), max),
                root.val);
        return Math.max(Math.max(leftMax + root.val, rightMax + root.val),
                root.val);
    }

【Leetcode】Binary Tree Maximum Path Sum

原文:http://blog.csdn.net/yeqiuzs/article/details/51623540

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!