๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
์•Œ๊ณ ๋ฆฌ์ฆ˜/๋ฌธ์ œ

[์ž๋ฐ”] Leetcode 637 - Average of Levels in Binary Tree

by applemango2021 2021. 3. 5.

leetcode.com/problems/average-of-levels-in-binary-tree/

 

Average of Levels in Binary Tree - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

๊ธฐ์ดˆ BFS๋ฌธ์ œ์ธ๋ฐ, BFS๋กœ ํ’€ ์ˆ˜ ์žˆ์Œ์„ ํŒŒ์•…ํ•˜๋Š” ๋ฐ ์˜ค๋ž˜ ๊ฑธ๋ ธ๋‹ค. ์Šฌํ”„๋‹ค.

 

root๋ฅผ Queue<TreeNode> queue์— ๋„ฃ์€ ๋‹ค์Œ์—, ํ•˜๋‚˜์”ฉ ๋ฝ‘์œผ๋ฉด์„œ left์™€ right ๋…ธ๋“œ๋ฅผ ๋‹ค์‹œ queue์— ๋„ฃ์–ด์ค€๋‹ค.

while๋ฌธ์„ ํƒ€๋ฉด์„œ ํ•œ ๋ ˆ๋ฒจ์˜ ๋…ธ๋“œ๊ฐœ์ˆ˜๊ฐ€ ๋ณ€์ˆ˜ size์— ๋“ค์–ด๊ฐˆ ๊ฒƒ์ด๊ณ , ๊ทธ size๋งŒํผ for๋ฌธ์„ ํƒ€๋ฉด์„œ ๋‹ค์‹œ ๊ทธ ๋…ธ๋“œ๋“ค์˜ ์ž์‹ ๋…ธ๋“œ๋“ค์„ ๋„ฃ์–ด์ค€๋‹ค. ์ด๋•Œ sum๋ณ€์ˆ˜์— ๊ฐ ๋…ธ๋“œ์˜ val๋„ ๋„ฃ์–ด์ค€๋‹ค.

for๋ฌธ์„ ๋‚˜์˜ค๊ณ  ๋‚˜์„œ๋Š” ์—ฌํƒœ๊นŒ์ง€ ๊ณ„์‚ฐ๋œ sum์„ size๋กœ ๋‚˜๋ˆ„๋ฉด ํ•ด๋‹น ๋ ˆ๋ฒจ์˜ ํ‰๊ท ๊ฐ’์„ ๊ตฌํ•  ์ˆ˜ ์žˆ๊ฒŒ ๋œ๋‹ค. 

     3
    / \
 9    20
        / \
     15 7

๋ฌธ์ œ์—์„œ ์ฃผ์–ด์ง„ ์œ„ ์˜ˆ์‹œ๋กœ ์ƒ๊ฐํ•ด๋ณด๋ฉด, 

root์ธ 3์ผ ๋•Œ์—๋Š” for๋ฌธ์„ ํƒ€๋ฉด์„œ queue์— 9์™€ 20์ด ๋“ค์–ด๊ฐˆ ๊ฒƒ์ด๊ณ , ๊ทธ ๋‹ค์Œ๋ฒˆ while์„ ๋Œ ๋•Œ์—๋Š” size=2๊ฐ€ ๋˜๋ฉด์„œ for๋ฌธ์„ 2๋ฒˆ ๋Œ๊ฒŒ ๋œ๋‹ค. ์ด๋•Œ 9์™€ 20์€ ๋ชจ๋‘ pop()๋˜์ง€๋งŒ, ๊ทธ ์ž์‹๋…ธ๋“œ๋“ค์ด ๋‹ค์‹œ add()๋˜๊ณ , ๋™์‹œ์— sum ๋ณ€์ˆ˜์— 9์™€ 20์ด ๋”ํ•ด์ง€๊ฒŒ ๋œ๋‹ค. 

class Solution {
    public List<Double> averageOfLevels(TreeNode root) {
        
        //ํ‰๊ท ๊ฐ’์„ ๋‹ด์„ List๋ณ€์ˆ˜
        List<Double> avg = new ArrayList<>();
        
        if(root==null) return avg;
        
        
        //Queue๋ฅผ ์ƒ์„ฑํ•˜์—ฌ root ์ถ”๊ฐ€
        Queue<TreeNode> que  = new LinkedList<>();
        que.add(root);
        
        TreeNode curr;
        while(!que.isEmpty()){
            int size = que.size();
            double sum = 0;
            
            //๊ฐ ๋ ˆ๋ฒจ์— ์กด์žฌํ•˜๋Š” ๋…ธ๋“œ์˜ ๊ฐœ์ˆ˜๋งŒํผ for๋ฌธ์„ ํƒ€๋ฉด์„œ ๋…ธ๋“œ๋ฅผ poll()
            for(int i=0;i<size;i++){
                curr = que.poll();
                sum += curr.val;
                
                if(curr.left!=null) que.add(curr.left);
                if(curr.right!=null) que.add(curr.right);
            }
            
            //avg์— ํ‰๊ท ๊ฐ’ ์ €์žฅ 
            avg.add(sum/size);
        }
        
        
        return avg;
    }

}