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:

  1. The range of node's value is in the range of 32-bit signed integer.
     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     vector<double> averageOfLevels(TreeNode* root) {
    13          vector<double> vet;
    14          if (root == NULL)
    15              return vet;
    16          stack<TreeNode*> stacknode;
    17          stacknode.push(root);
    18          while (stacknode.size())
    19          {
    20              double sum = 0;
    21              int count = stacknode.size();
    22              stack<TreeNode*> stacknode1 = stacknode;
    23              while (stacknode.size())
    24              {
    25                  TreeNode* pNode = stacknode.top();
    26                  sum += pNode->val;
    27                  stacknode.pop();
    28              }
    29              vet.push_back(sum / count);
    30              while (stacknode1.size())
    31              {
    32                  TreeNode* pNode1 = stacknode1.top();
    33                  if (pNode1->right)
    34                      stacknode.push(pNode1->right);
    35                  if (pNode1->left)
    36                      stacknode.push(pNode1->left);
    37                  stacknode1.pop();
    38              }
    39             
    40          }
    41          return vet;
    42     }
    43 };

     

posted on 2017-08-02 10:04  无惧风云  阅读(138)  评论(0编辑  收藏  举报