zoukankan      html  css  js  c++  java
  • Average of Levels in Binary Tree

    https://leetcode.com/problems/average-of-levels-in-binary-tree/#/description

    求出二叉树每层的均值,这个就是层序遍历的变种,没什么好说的。只是test case 里有INT_MAX-1,这个就很烦了,我没想到什么好办法,就把数字全都专程double 来处理了。

    思路用dfs 或者bfs 都可以,这里我采用了dfs,有个坑是给vector 赋值的时候是拷贝的,所以尽量用指针

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        void dfsIter(TreeNode *root, int level, vector<vector<double>*>& rets) {
            if (root == nullptr) return;
    
            vector<double> *l;
            if (rets.size() <= level) {
                l = new vector<double>();
                rets.push_back(l);
            } else {
                l = rets.at(level);
            }
    
            l->push_back(root->val);
            dfsIter(root->right, level+1, rets);
            dfsIter(root->left, level+1, rets);
        }
        vector<double> averageOfLevels(TreeNode* root) {
            if (root == nullptr) return vector<double>();
            vector<vector<double>*> levels;
            vector<double> result;
            dfsIter(root, 0, levels);
            for (auto level : levels) {
                double sum = 0;
                for (int n : *level) {
                    sum += (double)n;
                }
                result.push_back((double)sum / (double)level->size());
            }
        
            return result;
        }
    };
  • 相关阅读:
    MySQL主从复制原理
    MySQL调优
    apache禁止php解析--安全
    apache禁止指定的user_agent访问
    python---日常练习
    字符、字节的概念和区别;编码概念
    Django模型初识
    git安装
    Django--Hello
    fillder---断言/打断点,更改提交数据
  • 原文地址:https://www.cnblogs.com/agentgamer/p/7212050.html
Copyright © 2011-2022 走看看