leetcode637 (average value of binary trees: BFS traversal of binary trees)

Given a non-empty binary tree, return an array consisting of the average value of each level of nodes.

Example 1:
Input:
[3,9,20,null,null,15,17]
Output: [3, 14.5, 11]
Explanation:
The average value of layer 0 is 3, layer 1 is 14.5, and layer 2 is 11. So it returns [3, 14.5, 11].

Solution: This problem is a simple binary tree traversal problem. Both the BFS method and the DFS method can be realized. Here I mainly want to talk about the BFS method, because the BFS algorithm is actually traversed layer by layer according to the sequence of layers. The requirement of finding the layer average of this question is very consistent. The specific method is to first add the root node to the queue that the BFS algorithm needs to maintain, and then traverse according to the layer order. In the process of traversal, we have to take it out every timeCurrent queueCalculate the average value of all the elements in the queue, and add the child nodes of the elements in the queue to the queue.

class Solution {
    
    
    public List<Double> averageOfLevels(TreeNode root) {
    
    
         if(root==null)
             return new ArrayList<>();
             /*
              * res用于存储结果
              * Nodes是BFS中需要用到的队列
              * list用于临时存储每一层的结点key值
              */
         List<Double>res=new ArrayList<>();
         List<Integer>list=new ArrayList<>();
         Queue<TreeNode>Nodes=new LinkedList<>();
         Nodes.add(root);
         while(!Nodes.isEmpty()){
    
    
             TreeNode node=null;
             int size=Nodes.size();
           for(int i=0;i<size;i++){
    
    
               node=Nodes.poll();
               list.add(node.val);
               if(node.left!=null)
                   Nodes.add(node.left);
               if(node.right!=null)
                   Nodes.add(node.right);
           }
           res.add(layerAverage(list));
           list.clear();
         }
           return res;
    }
    private double layerAverage(List<Integer>list){
    
    
        double sum=0;
        for(int x:list){
    
    
            sum+=x;
        }
        return sum/list.size();
    }
}

Guess you like

Origin blog.csdn.net/CY2333333/article/details/108553639