[LeetCode] Average of Levels in Binary Tree 二叉樹的層平均值


 

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.

 

這道題讓我們求一個二叉樹每層的平均值,那么一看就是要進行層序遍歷了,直接上queue啊,如果熟悉層序遍歷的方法,那么這題就沒有什么難度了,直接將每層的值累計加起來,除以該層的結點個數,存入結果res中即可,參見代碼如下:

 

解法一:

class Solution {
public:
    vector<double> averageOfLevels(TreeNode* root) {
        if (!root) return {};
        vector<double> res;
        queue<TreeNode*> q{{root}};
        while (!q.empty()) {
            int n = q.size();
            double sum = 0;
            for (int i = 0; i < n; ++i) {
                TreeNode *t = q.front(); q.pop();
                sum += t->val;
                if (t->left) q.push(t->left);
                if (t->right) q.push(t->right);
            }
            res.push_back(sum / n);
        }
        return res;
    }
};

 

下面這種方法雖然是利用的遞歸形式的先序遍歷,但是其根據判斷當前層數level跟結果res中已經初始化的層數之間的關系對比,能把當前結點值累計到正確的位置,而且該層的結點數也自增1,這樣我們分別求了兩個數組,一個數組保存了每行的所有結點值,另一個保存了每行結點的個數,這樣對應位相除就是我們要求的結果了,參見代碼如下:

 

解法二:

class Solution {
public:
    vector<double> averageOfLevels(TreeNode* root) {
        vector<double> res, cnt;
        helper(root, 0, cnt, res);
        for (int i = 0; i < res.size(); ++i) {
            res[i] /= cnt[i];
        }
        return res;
    }
    void helper(TreeNode* node, int level, vector<double>& cnt, vector<double>& res) {
        if (!node) return;
        if (res.size() <= level) {
            res.push_back(0);
            cnt.push_back(0);
        }
        res[level] += node->val;
        ++cnt[level];
        helper(node->left, level + 1, cnt, res);
        helper(node->right, level + 1, cnt, res);
    }
};

 

類似題目:

Binary Tree Level Order Traversal II

Binary Tree Level Order Traversal

 

參考資料:

https://discuss.leetcode.com/topic/95567/java-solution-using-dfs-with-full-comments

 

LeetCode All in One 題目講解匯總(持續更新中...) 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM