Leetcode 637. Average of Levels in Binary Tree(Easy)

1.题目

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:

  1. The range of node's value is in the range of 32-bit signed integer.
翻译:给定一个非空的二叉树,返回序列中每一层节点的平均值。

2.思路

广度优先,层序遍历的方式。难点就是在,如何判断每一层结束了。两种方法可以判断一层遍历完,一种方式是在结尾加个特殊标记null结点,一种是数清楚每一层节点的个数。这道题中,我采用计数的方式。(因为加标记的方法没过~~)

3.算法

class Solution {
    public List<Double> averageOfLevels(TreeNode root) {
        //层序遍历
//         此方法没通过,因为我是在queue中加入左孩子、右孩子之后都加了null,这样肯定是不对的。        
//         ArrayList<Double> res=new ArrayList();
//         Queue<TreeNode> mQueue=new LinkedList();
//         int count=0;
//         int per=0;
//         double average=0;
        
//         mQueue.add(root);
//         mQueue.add(null);
        
//         while(!mQueue.isEmpty()){
//             TreeNode now=mQueue.poll();
//             if(now!=null){
//                 count+=now.val;
//                 per++; 
//                 if(now.left!=null)mQueue.add(now.left);
//                 if(now.right!=null)mQueue.add(now.right);
//                 mQueue.add(null);
//             }else{
//                 if(per!=0){
//                     average=(double)count/per;
//                     res.add(average);
//                     count=0;
//                     per=0;
//                 }  
//             }
//         }
//         return res;     
        
        ArrayList<Double> res=new ArrayList();
        Queue<TreeNode> mQueue=new LinkedList();
        long count=0;
        int per=0;
        double average=0;
        int size=0;
        TreeNode now;
        mQueue.add(root);//一定要首先把根结点加进来
        while(!mQueue.isEmpty()){
            size=mQueue.size();//这句是关键,判断此次,要处理几个节点
            for(int i=0;i<size;i++){
                now=mQueue.poll();
                count+=now.val;
                if(now.left!=null)mQueue.add(now.left);
                if(now.right!=null)mQueue.add(now.right);
            }
            average=(double)count/size;
            res.add(average);
            count=0;
        }
        return res;
    }
}

4.总结

循环的结束条件,非常重要。要找对判断循环结束的条件。

猜你喜欢

转载自blog.csdn.net/crab0314/article/details/79738730
今日推荐