LeetCode-124 Binary Tree Maximum Path Sum

來源:互聯網
上載者:User

標籤:

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. 就在root.left子樹中;2. 就在root.right子樹中;3.包含root節點,一部分在root.left中,另一部分在root.right中。

我們記錄兩個資料,全域變數max表示全域的最大值,局部變數currentMax表示經過當前root節點的路徑的最大值。如所示

在以-9為根的子樹中,max=7, currentMax=(-9+7)=-2;

在以3為根節點的子樹中,max=11,currentMax=(6+3)=9;

在以1為根節點的子樹中,max=11, currentMax=(1+9)=10;

最後,我們想要的結果是max;

本題需要注意遞迴方法的傳回值。代碼如下:

 1 public int maxPathSum(TreeNode root) { 2         if(root == null) 3             return 0; 4         maxPathSumHelper(root); 5         return this.max; 6     } 7      8     public int max = Integer.MIN_VALUE; 9     public int maxPathSumHelper(TreeNode root) {10         if(root == null)11             return 0;12         int leftMax = 0;13         int rightMax = 0;14         15         int returnValue = root.val;16         max = Math.max(root.val, max);17         if(root.left != null) {18             leftMax = maxPathSumHelper(root.left);19             max = Math.max(max, Math.max(leftMax, leftMax+root.val));20             returnValue = Math.max(returnValue, leftMax+root.val);21         }22         if(root.right != null) {23             rightMax = maxPathSumHelper(root.right);24             max = Math.max(max, Math.max(rightMax, rightMax+root.val));25             returnValue = Math.max(returnValue, rightMax+root.val);26         }27         if(root.left != null && root.right != null) {28             max = Math.max(max,  root.val+leftMax+rightMax);29         }30         31         return returnValue;32     }

 

LeetCode-124 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.