[LeetCode][Java] Binary Tree Maximum Path Sum

來源:互聯網
上載者:User

標籤:leetcode   java   binary tree maximum   

題目:

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      /      2   3
返回   6.

演算法分析:

    1) Recursively solve this problem

    2) Get largest left sum and right sum

    3) Compare to the stored maximum

  * 這裡有一個地方要想明白,最短路徑結果有四種可能,當前加左,當前加右,當前自己,當前加左、右子樹的return值

  * 而return值,有三種可能,當前加左,當前加右,當前自己。

  * 這裡return裡不是當前加左右子樹,也就是不能把left和right加起來了...因為只是一條路..,故不符合題目要求。

  * 在這裡,函數的返回值定義為以自己為根的一條從根到子結點的最長路徑


AC代碼:

<span style="font-family:Microsoft YaHei;font-size:12px;">/** * 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)     {    int max[] = new int[1];     max[0] = Integer.MIN_VALUE;    calculateSum(root, max);    return max[0];    }         public int calculateSum(TreeNode root, int[] max)     {    if (root == null)    return 0;         int left = calculateSum(root.left, max);    int right = calculateSum(root.right, max);         int current = Math.max(root.val, Math.max(root.val + left, root.val + right));         max[0] = Math.max(max[0], Math.max(current, left + root.val + right));         return current;    }}</span>

著作權聲明:本文為博主原創文章,轉載註明出處

[LeetCode][Java] Binary Tree Maximum Path Sum

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.