zoukankan      html  css  js  c++  java
  • 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:

    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 };
  • 相关阅读:
    快读
    状态压缩-动态规划
    数论入门_扩展欧几里得算法
    luogu P3383线性筛素数(埃氏筛)
    luogu P1843奶牛晒衣服
    git 常用方法
    javascript 数组排序
    深入理解javascript函数参数
    深入理解call apply bind方法
    移动H5前端性能优化
  • 原文地址:https://www.cnblogs.com/wujufengyun/p/7272358.html
Copyright © 2011-2022 走看看