标签:top logs arraylist sans tree nod evel des link
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:
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 List<Double> averageOfLevels(TreeNode root) { List < Double > res = new ArrayList < > (); Queue<TreeNode> q=new LinkedList<>(); q.add(root); while(!q.isEmpty()) { int n = q.size(); double sum = 0.0; for(int i = 0; i<n;i++) //这个地方设计的比较巧妙,用来计算一层的节点 { TreeNode x = q.poll(); sum += x.val; if(x.left != null) q.add(x.left); if(x.right != null) q.add(x.right);//同q.offer } res.add(sum / n); } return res; }
637. Average of Levels in Binary Tree
标签:top logs arraylist sans tree nod evel des link
原文地址:http://www.cnblogs.com/wxshi/p/7598545.html