leetcode编程记录13 #637 Average of Levels in Binary Tree

来源:互联网 发布:python 量化 开发环境 编辑:程序博客网 时间:2024/06/02 00:39

leetcode编程记录13 #637 Average of Levels in Binary Tree

标签(空格分隔): leetcode


这次的题目是有关树的简单问题,按要求输出树的每一层的数据就可以了。

题目如下:
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 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.

题目分析与理解:
题目给定的输入是一棵树,然后要求我们对树进行分层,然后求出树的每一层的平均值,最后将这些数据返回。通过对题目大致的分析,我们有了一个初步的算法,那就是对给定的树进行遍历,将同一层也就是同一深度的树的节点值和节点的计数值存在一个哈希表中,最后返回这些值,代码如下:

/** * 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) {        if (root!=NULL) {            putInMap(root, 1);        }        std::vector<double> result;        for (int i = 1; i < m.size() + 1; i++) {            result.push_back(m[i].first / m[i].second);        }        return result;    }private:    std::map<int, pair<double, int>> m;    void putInMap(TreeNode* root, int num) {        if (root != NULL) {            m[num].first += root->val;            m[num].second++;            putInMap(root->left, num + 1);            putInMap(root->right, num + 1);         }    }};
原创粉丝点击