637. 바이너리 트리 두 갈래 나무의 평균 레벨

2159 단어
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:
  • The range of node's value is in the range of 32-bit signed integer.

  • 사고방식[방법1]은 각 층의 결점 총수와 결점과 합을 깊이 있게 기록한다.
    /**
     * 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:
        vector averageOfLevels(TreeNode* root) {
            vector count;
            vector res;
            average(root,0,count,res);
            for(int i=0;i &count, vector &sum){
            if(!root) return;
            if(ival;
                count[i]++;
            }
            else{
                sum.push_back(1.0*root->val);
                count.push_back(1);
            }
            average(root->left,i+1,count,sum);
            average(root->right,i+1,count,sum);
        }
    };
    
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public List averageOfLevels(TreeNode root) {
            List count=new ArrayList<>();
            List res=new ArrayList<>();
            average(root,0,count,res);
            for(int i=0;i count, List sum){
            if(root==null) return;
            if(i

    좋은 웹페이지 즐겨찾기