MCPcopy Create free account
hub / github.com/ROUTINE-STUDY/Algorithm / Sanghoo

Class Sanghoo

LeetCode/BFS/104. Maximum Depth of Binary Tree/Sanghoo.java:20–55  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

18}
19
20public class Sanghoo {
21
22 public static int maxDepth(TreeNode root) {
23 if(root == null) return 0;
24
25 Queue<TreeNode> queue = new ArrayDeque();
26 int count = 0;
27
28 queue.offer(root); // root 노드 삽입
29
30 while(!queue.isEmpty()) {
31 int size = queue.size(); // 큐 사이즈는 안쪽 for문 안에서 변하므로 안쪽 for문 전 고정
32
33 // 노드를 하나씩 꺼내(선입선출) 자식 노드들이 있으면 큐에 삽입
34 for(int i=0; i<size; i++) {
35 TreeNode node = queue.poll();
36 if(node.left != null) {
37 queue.offer(node.left);
38 }
39 if(node.right != null) {
40 queue.offer(node.right);
41 }
42 }
43
44 count++; // 안쪽 for문 당 1 depth 추가, 그림으로 이해하는게 빠른듯
45 }
46 return count;
47 }
48
49 public static void main(String[] args) {
50 TreeNode root = new TreeNode(3,
51 new TreeNode(9, null, null),
52 new TreeNode(20, new TreeNode(15), new TreeNode(7)));
53 System.out.println(maxDepth(root));
54 }
55}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected