码迷,mamicode.com
首页 > 其他好文 > 详细

【Leetcode】Binary Tree Maximum Path Sum

时间:2016-06-10 11:08:38      阅读:168      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!