Binary Tree Maximum Path Sum leetcode java


題目

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.

 

題解

 遞歸求解。

 取當前點和左右邊加和,當前點的值中最大的作為本層返回值。並在全局維護一個max。使用數組,因為是引用類型。所以在遞歸過程中可以保存結果。

代碼如下:

 1      public  int maxPathSum(TreeNode root) {
 2          int[] max =  new  int[1];
 3         max[0] = Integer.MIN_VALUE;
 4         findmax(root,max);
 5          return max[0];
 6     }
 7     
 8      public  int findmax(TreeNode root,  int[] max){
 9          if(root== null)
10              return 0;
11         
12          int left = findmax(root.left,max);
13          int right = findmax(root.right,max);
14         
15          int ans = Math.max(root.val,Math.max(root.val+left, root.val+right));
16         
17         max[0] = Math.max(max[0],Math.max(ans,root.val+left+right));
18         
19          return ans;
20         
21     }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM