637. Average of Levels in Binary Tree

    xiaoxiao2024-05-06  104

    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 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.

    方法1:

    思路:

    level order traversal。数据点test到了INT_MAX,IN_MIN注意防止overflow。

    易错点

    需要用double或者long来防止overflow /** * 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) return {}; vector<double> result; queue<TreeNode*> q; q.push(root); while (!q.empty()) { int sz = q.size(); double sum = 0; for (int i = 0; i < sz; i++) { auto top = q.front(); q.pop(); sum += top -> val; if (top -> left) q.push(top -> left); if (top -> right) q.push(top -> right); } result.push_back(sum / (double) sz); } return result; } };
    最新回复(0)