日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Leetcode: Binary Tree Maximum Path Sum

發布時間:2025/3/19 编程问答 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Leetcode: Binary Tree Maximum Path Sum 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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.

難度:75.?

參見了他人的思路,這道題是求樹的路徑和的題目,不過和平常不同的是這里的路徑不僅可以從根到某一個結點,而且路徑可以從左子樹某一個結點,然后到達右子樹的結點,就像題目中所說的可以起始和終結于任何結點。函數的返回值定義為以自己為根的一條從根到葉子結點的最長路徑,這個返回值是為了提供給它的父結點計算自身的最長路徑用。這樣一來,一個結點自身的最長路徑就是它的左子樹返回值(如果大于0的話),加上右子樹的返回值(如果大于0的話),再加上自己的值。在過程中求得當前最長路徑時比較一下是不是目前最長的,如果是則更新。算法的本質還是一次樹的遍歷,所以復雜度是O(n)。而空間上仍然是棧大小O(logn)。注意這里path的存值方式是個問題,如果用一個integer變量代入recursion的話,函數無法對實參造成改變,所以用了一個對象ArrayList<Integer> res的第一個元素來存最大的path值

1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public int maxPathSum(TreeNode root) { 12 if (root == null) return 0; 13 ArrayList<Integer> res = new ArrayList<Integer>(); 14 res.add(Integer.MIN_VALUE); 15 FindMaxSum(root, res); 16 return res.get(0); 17 } 18 19 public int FindMaxSum(TreeNode root, ArrayList<Integer> res) { 20 if (root == null) { 21 return 0; 22 } 23 int leftsum = FindMaxSum(root.left, res); 24 int rightsum = FindMaxSum(root.right, res); 25 int maxsum = root.val + (leftsum>0? leftsum : 0) + (rightsum>0? rightsum : 0); 26 if (maxsum > res.get(0)) res.set(0, maxsum); 27 return root.val + Math.max(leftsum, Math.max(rightsum, 0)); 28 } 29 }

?

總結

以上是生活随笔為你收集整理的Leetcode: Binary Tree Maximum Path Sum的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。