[LeetCode] 637.Average of Levels in Binary Tree

来源:互联网 发布:mac os最新版本 编辑:程序博客网 时间:2024/06/07 01:21

[LeetCode] 637.Average of Levels in Binary Tree

  • 题目描述
  • 解题思路
  • 实验代码

题目描述

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

Example:
Input:
  3
  /   \
  9  20
   /   \
  15  7 
Output: [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:
The range of node’s value is in the range of 32-bit signed integer.

解题思路

题目意思很好理解,就是找到每一层结点的值的和的平均值。这道题关键的难点是怎么找到同一层的结点。我这里使用了vector和queue两个容器,利用其中的相关操作就能解决这个问题,具体过程见代码。

实验代码

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    vector<double> averageOfLevels(TreeNode* root) {        vector<double> v;        queue<TreeNode*> q;        q.push(root);        while (!q.empty()) {            long temp = 0;            int s = q.size();            for (int i = 0; i < s; i++) {                TreeNode* t = q.front();                q.pop();                if(t->left) q.push(t->left);                if(t->right) q.push(t->right);                temp += t->val;            }            v.push_back((double)temp/s);        }        return v;    }};
原创粉丝点击