|
| 1 | +/** |
| 2 | + * Definition for a binary tree node. |
| 3 | + * class TreeNode { |
| 4 | + * val: number |
| 5 | + * left: TreeNode | null |
| 6 | + * right: TreeNode | null |
| 7 | + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { |
| 8 | + * this.val = (val===undefined ? 0 : val) |
| 9 | + * this.left = (left===undefined ? null : left) |
| 10 | + * this.right = (right===undefined ? null : right) |
| 11 | + * } |
| 12 | + * } |
| 13 | + */ |
| 14 | + |
| 15 | +// O(n) time, 모든 노드를 한 번씩 방문 |
| 16 | +// O(h) for DFS / O(w) for BFS space, DFS는 재귀 호출 깊이 (h = 트리 높이), BFS는 큐에 들어가는 최대 노드 수 (w = 최대 너비) |
| 17 | + |
| 18 | +class TreeNode { |
| 19 | + val: number; |
| 20 | + left: TreeNode | null; |
| 21 | + right: TreeNode | null; |
| 22 | + constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { |
| 23 | + this.val = val === undefined ? 0 : val; |
| 24 | + this.left = left === undefined ? null : left; |
| 25 | + this.right = right === undefined ? null : right; |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +// BFS 풀이 |
| 30 | +function maxDepth(root: TreeNode | null): number { |
| 31 | + if (root === null) return 0; |
| 32 | + |
| 33 | + const queue: TreeNode[] = [root]; |
| 34 | + let depth = 0; |
| 35 | + |
| 36 | + while (queue.length > 0) { |
| 37 | + const levelSize = queue.length; |
| 38 | + |
| 39 | + for (let i = 0; i < levelSize; i++) { |
| 40 | + const node = queue.shift(); |
| 41 | + if (node) { |
| 42 | + if (node.left) queue.push(node.left); |
| 43 | + if (node.right) queue.push(node.right); |
| 44 | + } |
| 45 | + } |
| 46 | + depth++; |
| 47 | + } |
| 48 | + return depth; |
| 49 | +} |
| 50 | + |
| 51 | +// DFS 풀이 |
| 52 | +// function maxDepth(root: TreeNode | null): number { |
| 53 | +// if (root === null) return 0; |
| 54 | +// const left = maxDepth(root.left); |
| 55 | +// const right = maxDepth(root.right); |
| 56 | +// return Math.max(left, right) + 1; |
| 57 | +// } |
0 commit comments