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 7Output: [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.
给定一颗二叉树,求出二叉树每一层节点的平均值,第一反应是使用二叉树的层次遍历,先回忆一下二叉树的层次遍历
void level_tree(bintree t){ Queue q; bintree temp; if(!t){ printf("the tree is empty\n"); return ; } q.add(t); while(!q.isEmpty){ t=poll(q); //出队 printf("%c ",t.val); if(t.left != null){ q.add(t.left); } if(t.right != null){ q.add(t.right); } } }
public ListaverageOfLevels(TreeNode root) { List < Double > res = new ArrayList < > (); Queue q=new LinkedList<>(); q.add(root); while(!q.isEmpty()) { int n = q.size(); double sum = 0.0; for(int i = 0; i