[Leetcode in Java] 637. Average of Levels in Binary Tree


Posted by LarsonKao on 2022-05-26

637. Average of Levels in Binary Tree

Link

難易度 : Easy

依照對岸Carl大神的練習順序,接下來會連做10題類似觀念的題目,題號如下 :

question1
question2

題目要求回傳各層所有node val的平均值,作法大同小異,遍尋各層時累加並且計算即可。

    class Solution
    {
        public List<Double> averageOfLevels(TreeNode root)
        {
            Queue<TreeNode> queue = new LinkedList<TreeNode>();
            List<Double> result = new ArrayList<Double>();
            TreeNode current;
            if(root==null) 
            {
                return result;
            }
            queue.add(root);
            while(!queue.isEmpty()) 
            {
                int size = queue.size();
                double sum = 0;
                //遍尋此層數量的所有node 之後加入的不與理會
                for(int i=0;i<size;i++) 
                {
                    current = queue.poll();
                    //累加各層的val sum
                    sum+=current.val;
                    if(current.left!=null) 
                    {
                        queue.add(current.left);
                    }
                    if(current.right!=null) 
                    {
                        queue.add(current.right);
                    }
                }
                result.add(sum/size);
            }
            return result;
        }
    }

result


#Leetcode #java #algorithm #Queue #binary tree #BFS







Related Posts

【單元測試的藝術】Chap 10: 遺留程式碼

【單元測試的藝術】Chap 10: 遺留程式碼

Day 14-higher-lower game

Day 14-higher-lower game

學習 Git (2) - 開始使用 Git 進行版本控制

學習 Git (2) - 開始使用 Git 進行版本控制


Comments