层次遍历,计算每一层的节点值,然后求平均值。

class Solution {
public:
    vector<double> averageOfLevels(TreeNode* root) {
        vector<double> D;
        if (root != NULL)
        {
            queue<TreeNode> Q;

            TreeNode node = TreeNode(root->val);
            node.left = root->left;
            node.right = root->right;
            Q.push(node);

            while (!Q.empty())
            {
                //出队列
                vector<double> L;
                vector<TreeNode> T;
                L.clear();
                double sum = 0.0;
                while (!Q.empty())
                {
                    TreeNode livenode = Q.front();
                    Q.pop();
                    L.push_back(livenode.val);
                    T.push_back(livenode);
                }
                //计算L中的数值
                for (auto v : L)
                {
                    sum += v;
                }
                sum = sum / L.size();
                D.push_back(sum);

                //将左右子树放入队列
                for (auto t : T)
                {
                    if (t.left != NULL)
                    {
                        Q.push(*t.left);
                    }
                    if (t.right != NULL)
                    {
                        Q.push(*t.right);
                    }
                }
            }
        }
        return D;
    }
};

 

posted on 2018-09-26 16:21  Sempron2800+  阅读(121)  评论(0编辑  收藏  举报