637. Average of Levels in Binary Tree(Tree)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tangyuanzong/article/details/79955137

https://leetcode.com/problems/average-of-levels-in-binary-tree/description/

题目:求每一层元素的平均值

思路:BFS遍历

class Solution {
public:
    vector<double> averageOfLevels(TreeNode* root) {
          vector<double>result;
          if(!root) return result;

          TreeNode *q[10000];
          int num=1,num_1=1,next_num=0,l=0,r=1;

          q[l]=root;
          double sum=0;
          while(l<r){
               TreeNode *temp = q[l];
               num--;
               sum+=temp->val;
               if(temp->left) {
                  q[r]=temp->left;
                  r++;
                  next_num++;
               }
               if(temp->right) {
                  q[r]=temp->right;
                  r++;
                  next_num++;
               }
               if(num==0){
                  result.push_back(sum/num_1);
                  num=num_1=next_num;
                  next_num=0;
                  sum=0;
               }
              l++;
          }
        return result;
    }
};
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页