1、题目描述

Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.

leetCode题解之求二叉树每层的平均值

计算二叉树每一层的节点的数据域的平均值。

 

2、题目分析

使用广度优先遍历方法,逐层对二叉树进行访问,求均值。使用一个队列数据结构完成对二叉树的访问,队列(queue)的特点是FIFO,即先进先出,queue的几种常用的方法是:

queue::front()  :访问队首元素

queue:: pop()  删除队首元素

queue::push()  入队

queue:: back()  访问队尾元素

 1 vector<double> averageOfLevels(TreeNode* root) {
 2         
 3         vector<double> ave;
 4         queue<TreeNode*> q;
 5         q.push(root);
 6 
 7         while(!q.empty())
 8             {
 9                 double temp = 0.0;
10                 int s = q.size();
11                 for( int i = 0; i < s;i++ )
12                     {
13                         temp += q.front()->val;
14                         if(q.front()->left) q.push(q.front()->left);
15                         if(q.front()->right ) q.push(q.front()->right);
16                         q.pop();
17                     }
18                 ave.push_back(temp/s);
19 
20             }
21         return ave;
22         
23         
24         
25     }

 

 

3、代码

 

相关文章:

  • 2021-04-27
  • 2021-07-17
  • 2022-12-23
  • 2021-12-07
  • 2021-05-24
  • 2022-02-06
  • 2021-08-12
猜你喜欢
  • 2022-12-23
  • 2021-09-19
  • 2021-06-01
  • 2021-04-09
  • 2021-11-17
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案