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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

637. Average of Levels in Binary Tree

發布時間:2023/12/20 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 637. Average of Levels in Binary Tree 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1.問題描述

Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.Example 1:Input:3/ \9 20/ \15 7Output: [3, 14.5, 11]Explanation:The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].Note:1. The range of node's value is in the range of 32-bit signed integer.來自 <https://leetcode.com/problems/average-of-levels-in-binary-tree/description/>

2.題目分析

求二叉樹每一層的平均數,并存入到數組中,遍歷方法使用層序遍歷,關鍵是怎么判斷一層結束了,區別于層序遍歷的單隊列,這里使用了兩個隊列,一個存儲父節點層,另一個存儲子節點層,再父節點層遍歷完成后,計算均值并存儲,然后交換這兩個隊列,使得當前子節點層成為下一次計算的父節點層。結束的條件是兩個隊列都空了。需要注意的是,當父結點層存在,子結點層不存在,即最后一層時,并沒有計算最后一層均值,因此需要在循環結束時,計算最后一層均值并存儲。

3.C++代碼

//我的代碼:(beats 42%)vector<double> averageOfLevels(TreeNode* p){vector<double>r;queue<TreeNode*>q_root;queue<TreeNode*>q_child;q_root.push(p);int cnt = 0;double sum = 0;double aver = 0;while (!q_root.empty() || !q_child.empty()){if (!q_root.empty()){TreeNode *tmp = q_root.front();q_root.pop();if (tmp->left != NULL)q_child.push(tmp->left);if (tmp->right != NULL)q_child.push(tmp->right);cnt++;sum += tmp->val;}else{aver = sum / cnt;cnt = 0;sum = 0;q_root.swap(q_child);r.push_back(aver);}}aver = sum / cnt;r.push_back(aver);return r;}//改進版:(beats 74%)//只用一個隊列,每次大循環處理一行,而不是只處理一個結點//利用每一層的結點個數就是隊列的長度這一特點,減少一個隊列vector<double> averageOfLevels2(TreeNode* p){vector<double>r;queue<TreeNode*>q;q.push(p);int n = 0;double sum = 0;double aver = 0;while (!q.empty()){n = q.size();sum = 0;for (int i = 0; i < n; i++){TreeNode*tmp = q.front();q.pop();sum += tmp->val;if (tmp->left)q.push(tmp->left);if (tmp->right)q.push(tmp->right);}aver = sum / n;r.push_back(aver);}return r;}

總結

以上是生活随笔為你收集整理的637. Average of Levels in Binary Tree的全部內容,希望文章能夠幫你解決所遇到的問題。

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