/**
* 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;
}
}