Re: [閒聊] 每日LeetCode已回收

看板Marginalman作者 (みけねこ的鼻屎)時間2年前 (2023/06/15 10:45), 編輯推噓1(101)
留言2則, 2人參與, 2年前最新討論串348/719 (看更多)
https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/description/ 1161. Maximum Level Sum of a Binary Tree 返回最大的總和層數(每層),如果總和相同取較小的。 Example 1: https://assets.leetcode.com/uploads/2019/05/03/capture.JPG
Input: root = [1,7,0,7,-8,null,null] Output: 2 Explanation: Level 1 sum = 1. Level 2 sum = 7 + 0 = 7. Level 3 sum = 7 + -8 = -1. So we return the level with the maximum sum which is level 2. Example 2: Input: root = [989,null,10250,98693,-89388,null,null,null,-32127] Output: 2 思路: 1.用BFS去遍歷,每次算出來的都是當前層數和,如果當前和大於前面的才更新結果。 Java Code: ----------------------------------------------- class Solution { public int maxLevelSum(TreeNode root) { int max = root.val; int res = 1; Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); int level = 1; while (!queue.isEmpty()) { int size = queue.size(); int sum = 0; for (int i = 0; i < size; i++) { TreeNode node = queue.poll(); sum += node.val; if (node.left != null) { queue.offer(node.left); } if (node.right != null) { queue.offer(node.right); } } if (sum > max) { max = sum; res = level; } level++; } return res; } } ----------------------------------------------- -- https://i.imgur.com/YPBHGGE.jpg
-- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 122.100.75.86 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1686797108.A.041.html

06/15 10:46, 2年前 , 1F
大師
06/15 10:46, 1F

06/15 10:49, 2年前 , 2F
大師
06/15 10:49, 2F
文章代碼(AID): #1aYdiq11 (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1aYdiq11 (Marginalman)