5858
5959### 方法一:BFS
6060
61- 可以忽略一些细节,每次都统计当前遍历层级的数值和,当 BFS 结束时,最后一次数值和便是结果 。
61+ 我们可以使用广度优先搜索,逐层遍历二叉树,并在遍历到每一层时计算该层的节点值之和。遍历完成后,返回最后一层的节点值之和 。
6262
6363时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是树中节点的数目。
6464
@@ -79,12 +79,12 @@ class Solution:
7979 while q:
8080 ans = 0
8181 for _ in range (len (q)):
82- root = q.popleft()
83- ans += root .val
84- if root .left:
85- q.append(root .left)
86- if root .right:
87- q.append(root .right)
82+ node = q.popleft()
83+ ans += node .val
84+ if node .left:
85+ q.append(node .left)
86+ if node .right:
87+ q.append(node .right)
8888 return ans
8989```
9090
@@ -113,14 +113,14 @@ class Solution {
113113 int ans = 0 ;
114114 while (! q. isEmpty()) {
115115 ans = 0 ;
116- for (int n = q. size(); n > 0 ; -- n ) {
117- root = q. pollFirst ();
118- ans += root . val;
119- if (root . left != null ) {
120- q. offer(root . left);
116+ for (int k = q. size(); k > 0 ; -- k ) {
117+ TreeNode node = q. poll ();
118+ ans += node . val;
119+ if (node . left != null ) {
120+ q. offer(node . left);
121121 }
122- if (root . right != null ) {
123- q. offer(root . right);
122+ if (node . right != null ) {
123+ q. offer(node . right);
124124 }
125125 }
126126 }
@@ -150,12 +150,16 @@ public:
150150 queue<TreeNode* > q{{root}};
151151 while (!q.empty()) {
152152 ans = 0;
153- for (int n = q.size(); n ; --n ) {
154- root = q.front();
153+ for (int k = q.size(); k ; --k ) {
154+ TreeNode * node = q.front();
155155 q.pop();
156- ans += root->val;
157- if (root->left) q.push(root->left);
158- if (root->right) q.push(root->right);
156+ ans += node->val;
157+ if (node->left) {
158+ q.push(node->left);
159+ }
160+ if (node->right) {
161+ q.push(node->right);
162+ }
159163 }
160164 }
161165 return ans;
@@ -174,24 +178,23 @@ public:
174178 * Right *TreeNode
175179 * }
176180 */
177- func deepestLeavesSum(root *TreeNode) int {
181+ func deepestLeavesSum(root *TreeNode) (ans int) {
178182 q := []*TreeNode{root}
179- ans := 0
180183 for len(q) > 0 {
181184 ans = 0
182- for n := len(q); n > 0; n -- {
183- root = q[0]
185+ for k := len(q); k > 0; k -- {
186+ node : = q[0]
184187 q = q[1:]
185- ans += root .Val
186- if root .Left != nil {
187- q = append(q, root .Left)
188+ ans += node .Val
189+ if node .Left != nil {
190+ q = append(q, node .Left)
188191 }
189- if root .Right != nil {
190- q = append(q, root .Right)
192+ if node .Right != nil {
193+ q = append(q, node .Right)
191194 }
192195 }
193196 }
194- return ans
197+ return
195198}
196199```
197200
@@ -213,20 +216,19 @@ func deepestLeavesSum(root *TreeNode) int {
213216 */
214217
215218function deepestLeavesSum(root : TreeNode | null ): number {
216- const queue = [root ];
217- let res = 0 ;
218- while (queue .length !== 0 ) {
219- const n = queue .length ;
220- let sum = 0 ;
221- for (let i = 0 ; i < n ; i ++ ) {
222- const { val, left, right } = queue .shift ();
223- sum += val ;
224- left && queue .push (left );
225- right && queue .push (right );
219+ let q: TreeNode [] = [root ];
220+ let ans = 0 ;
221+ while (q .length ) {
222+ const nq: TreeNode [] = [];
223+ ans = 0 ;
224+ for (const { val, left, right } of q ) {
225+ ans += val ;
226+ left && nq .push (left );
227+ right && nq .push (right );
226228 }
227- res = sum ;
229+ q = nq ;
228230 }
229- return res ;
231+ return ans ;
230232}
231233```
232234
@@ -251,70 +253,32 @@ function deepestLeavesSum(root: TreeNode | null): number {
251253// }
252254// }
253255// }
254- use std :: cell :: RefCell ;
255256use std :: rc :: Rc ;
257+ use std :: cell :: RefCell ;
258+ use std :: collections :: VecDeque ;
259+
256260impl Solution {
257- fn dfs (root : & Option <Rc <RefCell <TreeNode >>>, depth : i32 , max_depth : & mut i32 , res : & mut i32 ) {
258- if let Some (node ) = root {
259- let node = node . borrow ();
260- if node . left. is_none () && node . right. is_none () {
261- if depth == * max_depth {
262- * res += node . val;
263- } else if depth > * max_depth {
264- * max_depth = depth ;
265- * res = node . val;
261+ pub fn deepest_leaves_sum (root : Option <Rc <RefCell <TreeNode >>>) -> i32 {
262+ let mut q = VecDeque :: new ();
263+ q . push_back (root );
264+ let mut ans = 0 ;
265+ while ! q . is_empty () {
266+ ans = 0 ;
267+ for _ in 0 .. q . len () {
268+ if let Some (Some (node )) = q . pop_front () {
269+ let node = node . borrow ();
270+ ans += node . val;
271+ if node . left. is_some () {
272+ q . push_back (node . left. clone ());
273+ }
274+ if node . right. is_some () {
275+ q . push_back (node . right. clone ());
276+ }
266277 }
267- return ;
268278 }
269- Self :: dfs (& node . left, depth + 1 , max_depth , res );
270- Self :: dfs (& node . right, depth + 1 , max_depth , res );
271- }
272- }
273-
274- pub fn deepest_leaves_sum (root : Option <Rc <RefCell <TreeNode >>>) -> i32 {
275- let mut res = 0 ;
276- let mut max_depth = 0 ;
277- Self :: dfs (& root , 0 , & mut max_depth , & mut res );
278- res
279- }
280- }
281- ```
282-
283- #### C
284-
285- ``` c
286- /* *
287- * Definition for a binary tree node.
288- * struct TreeNode {
289- * int val;
290- * struct TreeNode *left;
291- * struct TreeNode *right;
292- * };
293- */
294-
295- void dfs (struct TreeNode* root, int depth, int* maxDepth, int* res) {
296- if (!root->left && !root->right) {
297- if (depth == * maxDepth) {
298- * res += root->val;
299- } else if (depth > * maxDepth) {
300- * maxDepth = depth;
301- * res = root->val;
302279 }
303- return;
280+ ans
304281 }
305- if (root->left) {
306- dfs(root->left, depth + 1, maxDepth, res);
307- }
308- if (root->right) {
309- dfs(root->right, depth + 1, maxDepth, res);
310- }
311- }
312-
313- int deepestLeavesSum(struct TreeNode* root) {
314- int res = 0;
315- int maxDepth = 0;
316- dfs(root, 0, &maxDepth, &res);
317- return res;
318282}
319283```
320284
@@ -326,6 +290,8 @@ int deepestLeavesSum(struct TreeNode* root) {
326290
327291### 方法二:DFS
328292
293+ 我们可以使用深度优先搜索,递归遍历二叉树,并在遍历的过程中记录当前节点的深度,以及最大深度和最深叶子节点的和。遍历到当前节点时,如果当前节点的深度等于最大深度,则将当前节点的值加到最深叶子节点的和中;如果当前节点的深度大于最大深度,则将最大深度更新为当前节点的深度,并将最深叶子节点的和更新为当前节点的值。
294+
329295时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是树中节点的数目。
330296
331297<!-- tabs: start -->
@@ -417,25 +383,24 @@ class Solution {
417383 */
418384class Solution {
419385public:
420- int mx = 0;
421- int ans = 0;
422-
423386 int deepestLeavesSum(TreeNode* root) {
424- dfs(root, 1);
387+ int mx = 0, ans = 0;
388+ auto dfs = [ &] (auto&& dfs, TreeNode* root, int i) {
389+ if (!root) {
390+ return;
391+ }
392+ if (i == mx) {
393+ ans += root->val;
394+ } else if (i > mx) {
395+ mx = i;
396+ ans = root->val;
397+ }
398+ dfs(dfs, root->left, i + 1);
399+ dfs(dfs, root->right, i + 1);
400+ };
401+ dfs(dfs, root, 1);
425402 return ans;
426403 }
427-
428- void dfs (TreeNode* root, int i) {
429- if (!root) return;
430- if (i == mx) {
431- ans += root->val;
432- } else if (i > mx) {
433- mx = i;
434- ans = root->val;
435- }
436- dfs(root->left, i + 1);
437- dfs(root->right, i + 1);
438- }
439404};
440405```
441406
@@ -489,22 +454,59 @@ func deepestLeavesSum(root *TreeNode) int {
489454 */
490455
491456function deepestLeavesSum(root : TreeNode | null ): number {
492- let res = 0 ;
493- let maxDepath = 0 ;
494- const dfs = ({ val , left , right }: TreeNode , depth : number ) => {
495- if (left == null && right == null ) {
496- if (depth === maxDepath ) {
497- res += val ;
498- } else if (depth > maxDepath ) {
499- maxDepath = depth ;
500- res = val ;
501- }
457+ let [ans, mx] = [0 , 0 ];
458+ const dfs = (root : TreeNode | null , i : number ) => {
459+ if (! root ) {
502460 return ;
503461 }
504- left && dfs (left , depth + 1 );
505- right && dfs (right , depth + 1 );
462+ if (i > mx ) {
463+ mx = i ;
464+ ans = root .val ;
465+ } else if (i === mx ) {
466+ ans += root .val ;
467+ }
468+ dfs (root .left , i + 1 );
469+ dfs (root .right , i + 1 );
506470 };
507- dfs (root , 0 );
471+ dfs (root , 1 );
472+ return ans ;
473+ }
474+ ```
475+
476+ #### C
477+
478+ ``` c
479+ /* *
480+ * Definition for a binary tree node.
481+ * struct TreeNode {
482+ * int val;
483+ * struct TreeNode *left;
484+ * struct TreeNode *right;
485+ * };
486+ */
487+
488+ void dfs (struct TreeNode* root, int depth, int* maxDepth, int* res) {
489+ if (!root->left && !root->right) {
490+ if (depth == * maxDepth) {
491+ * res += root->val;
492+ } else if (depth > * maxDepth) {
493+ * maxDepth = depth;
494+ * res = root->val;
495+ }
496+ return;
497+ }
498+ if (root->left) {
499+ dfs(root->left, depth + 1, maxDepth, res);
500+ }
501+ if (root->right) {
502+ dfs(root->right, depth + 1, maxDepth, res);
503+ }
504+ }
505+
506+ int deepestLeavesSum(struct TreeNode* root) {
507+ int res = 0;
508+ int maxDepth = 0;
509+ dfs(root, 0, &maxDepth, &res);
508510 return res;
509511}
510512```
0 commit comments