leetcode - 637. Average of Levels in Binary Tree【广度优先遍历 + 辅助变量】

xiaoxiao2021-02-27  116

题目

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.

题意

给定一个非空二叉树,返回其每个层次上结点的平均值(数组形式)。

分析及解答

区分什么情况下用深度优先遍历,何时用广度优先遍历。合理定义及使用每一个变量。

public class Solution { public List<Double> averageOfLevels(TreeNode root) { List<Double> results = new ArrayList<>(); Queue<TreeNode> que = new LinkedList<>(); //1.注意每个变量的作用。 que.add(root); int count = 1,tmp_count = count; //记录当前处理层次,结点的数量。 double sum = 0;//记录当前层次结点的和。 int son_count = 0; //记录下一层次结点的数量。 //2.广度优先遍历 + 层次计数 + 周期性处理 while(!que.isEmpty()){ //3.当一个结点弹出队列的时候,需要做3件事情: //3.1. 求和(该层次) //3.2. 孩子进入队列。 //3.3. 层次计数减1.(若减一后为0,则进行层次平均值计算并保存,然后重新初始化相应的辅助变量) TreeNode node = que.poll(); sum += node.val; tmp_count --; if(node.left != null){ son_count ++; que.add(node.left); } if(node.right != null){ son_count ++; que.add(node.right); } if(tmp_count == 0){ results.add(sum / count); sum = 0; tmp_count = count = son_count; son_count = 0; } } return results; } }

转载请注明原文地址: https://www.6miu.com/read-15071.html

最新回复(0)