Lintcode 1115 · Average of Levels in Binary Tree (BFS/DFS 经典题)

1115 · Average of Levels in Binary Tree
Algorithms
Description
Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.
The range of node’s value is in the range of 32-bit signed integer.
Example
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].
Tags
Company
Facebook

解法1:DFS

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param root: the binary tree of the  root
     * @return: return a list of double
     */
    vector<double> averageOfLevels(TreeNode * root) {
        if (!root) return {};
        vector<double> avgs;
        vector<int> counts;

        helper(root, 0, avgs, counts);
        for (int i = 0; i < avgs.size(); i++) {
            avgs[i] /= 1.0 * counts[i];
        }
        return avgs;
    }
private:
    void helper(TreeNode*root, int depth, vector<double> &avgs, vector<int> &counts) {
        if (!root) return;
        if (depth == avgs.size()) {
            avgs.push_back(1.0 * root->val);
            counts.push_back(1);
        } else { //depth < avgs.size(). It is impossible that depth > avgs.size()
            //avgs.back() += 1.0 * root->val;   //不对
            //counts.back()++; //不对
            avgs[depth] += 1.0 * root->val;
            counts[depth]++;

        }
        if (root->left) helper(root->left, depth + 1, avgs, counts);
        if (root->right) helper(root->right, depth + 1, avgs, counts);
        return;
    }
};

解法2:BFS

class Solution {
public:
    /**
     * @param root: the binary tree of the  root
     * @return: return a list of double
     */
    vector<double> averageOfLevels(TreeNode * root) {
        if (!root) return {};
        vector<double> res;
        queue<TreeNode *> q;
        q.push(root);

        while (!q.empty()) {
            int qSize = q.size();
            double sum = 0.0;
            for (int i = 0; i < qSize; i++) {
                TreeNode *front = q.front();
                q.pop();
                sum += front->val;
                if (front->left) q.push(front->left);
                if (front->right) q.push(front->right);
            }
            res.push_back(sum / (1.0 * qSize));
        }
        return res;
    }
};

你可能感兴趣的:(宽度优先,深度优先,算法)