Maximum Depth of Binary Tree_BFS

BFS, Queue

Data Structure : Queue

Algorithm 1. ๋…ธ๋“œ ํƒ€์ž…์˜ ํ ์ƒ์„ฑ. 2. ํ๊ฐ€ ๋น„์–ด์žˆ์„ ๋•Œ๊นŒ์ง€ Poll, Offer ๋ฐ˜๋ณตํ•œ๋‹ค.( Poll ํ•˜๋Š” ๋™์‹œ์— Offer) 3. ๊ฐ ๋ ˆ๋ฒจ๋งˆ๋‹ค ๊นŠ์ด๋ฅผ +1์”ฉ ์ฆ๊ฐ€์‹œํ‚จ๋‹ค.

Technique & skill 1. ๋ฐ˜๋ณต๋ฌธ์˜ ์œ„์น˜์™€ ๊ตฌ์กฐ. ๋…ผ๋ฆฌ์ ์œผ๋กœ ์ƒ๊ฐํ•˜๊ธฐ!

Implement Algorithms in Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {//BFS, Queue
    public int maxDepth(TreeNode root) {
        //1.์ž๋ฃŒ๊ตฌ์กฐ ์ƒ์„ฑ
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int depth = 0;
        
        //2. ๋ฐ˜๋ณต๋ฌธ ๋Œ๋ฆฐ๋‹ค.
        //ํ๊ฐ€ ๋นŒ ๋•Œ๊นŒ์ง€ offer์™€ poll์„ ๋ฐ˜๋ณตํ•œ๋‹ค.
        while(!queue.isEmpty()) {
            int size = queue.size();
            
            //ํ ๊ฐฏ์ˆ˜๋งŒํผ pollํ•˜๊ณ  ๋‚˜์„œ ๊นŠ์ด +1 ์ฆ๊ฐ€์‹œํ‚จ๋‹ค.
            for(int i=0;i<size;i++) {//ํ์˜ ๊ฐฏ์ˆ˜๋งŒํผ pollํ•œ๋‹ค.
                TreeNode node = queue.poll();//pollํ•˜๋ฉด์„œ ๋™์‹œ์— ์™ผ์ชฝ ์ž์‹ ์˜ค๋ฅธ์ชฝ ์ž์‹ ๋„ฃ๋Š”๋‹ค!
                if(node.left != null) {queue.offer(node.left);}
                if(node.right != null) {queue.offer(node.right);}
            }
            depth++;//0->1->2->3
        }
        return depth;
    }
}

Last updated