|
| 1 | +/** |
| 2 | + * Definition for a binary tree node. |
| 3 | + */ |
| 4 | +function TreeNode(val, left, right) { |
| 5 | + this.val = (val === undefined ? 0 : val); |
| 6 | + this.left = (left === undefined ? null : left); |
| 7 | + this.right = (right === undefined ? null : right); |
| 8 | +} |
| 9 | +/* |
| 10 | + 이진 트리(Binary Tree)의 root 노드가 주어졌을 때, |
| 11 | + 트리의 최대 깊이(maximum depth)를 반환하는 함수. |
| 12 | +
|
| 13 | + 최대 깊이란: |
| 14 | + - 루트(root)에서 가장 먼 리프(leaf) 노드까지 |
| 15 | + 도달하는 경로에 포함된 "노드의 개수"를 의미함. |
| 16 | +
|
| 17 | + Example 1: |
| 18 | + Input: root = [3,9,20,null,null,15,7] |
| 19 | + Output: 3 |
| 20 | + 설명: |
| 21 | + 트리 구조는 다음과 같으며, |
| 22 | + 가장 깊은 경로(3 → 20 → 15 또는 3 → 20 → 7)의 노드 수는 3. |
| 23 | +
|
| 24 | + Example 2: |
| 25 | + Input: root = [1,null,2] |
| 26 | + Output: 2 |
| 27 | + 설명: |
| 28 | + 트리 구조는 1 → 2 형태이며 노드 수 2가 최대 깊이. |
| 29 | +
|
| 30 | + Constraints: |
| 31 | + - 트리의 노드 개수: 0 ~ 10^4 |
| 32 | + - 노드 값 범위: -100 ~ 100 |
| 33 | +*/ |
| 34 | + |
| 35 | +/** |
| 36 | + * @param {TreeNode} root |
| 37 | + * @return {number} |
| 38 | + */ |
| 39 | +var maxDepth = function(root) { |
| 40 | + |
| 41 | + if (root === null) return 0; |
| 42 | + |
| 43 | + const left = maxDepth(root.left); |
| 44 | + const right = maxDepth(root.right); |
| 45 | + |
| 46 | + return 1 + Math.max(left, right); |
| 47 | +}; |
| 48 | + |
| 49 | +// example1 |
| 50 | +const example1 = new TreeNode( |
| 51 | + 3, |
| 52 | + new TreeNode(9), |
| 53 | + new TreeNode(20, |
| 54 | + new TreeNode(15), |
| 55 | + new TreeNode(7) |
| 56 | + ) |
| 57 | +); |
| 58 | + |
| 59 | +// example2 |
| 60 | +const example2 = new TreeNode( |
| 61 | + 1, |
| 62 | + null, |
| 63 | + new TreeNode(2) |
| 64 | +); |
| 65 | + |
| 66 | + |
| 67 | +// maxDepth 함수 결과 출력 |
| 68 | +console.log("Example 1 maxDepth:", maxDepth(example1)); |
| 69 | +console.log("Example 2 maxDepth:", maxDepth(example2)); |
| 70 | + |
0 commit comments