• 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 };
  • 相关阅读:
    Scala并发编程react、loop代码实战具体解释
    Linux内核通知链模块
    STL栈的应用之表达式求值
    ansi 控制码表及颜色代码
    关于substring的char[]共享
    jQuery几个经典表单应用整理回想
    ShareSDK for Android 2.3.10已经公布
    cocos2dx坐标系
    一种Android数据请求框架
    css 小问题解决方法整理
  • 原文地址:https://www.cnblogs.com/wujufengyun/p/7272358.html
Copyright © 2020-2023  润新知