Skip to content

Commit 6791924

Browse files
committed
maximum depth of binary tree solution
1 parent da95352 commit 6791924

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val, left, right) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.left = (left===undefined ? null : left)
6+
* this.right = (right===undefined ? null : right)
7+
* }
8+
*/
9+
/**
10+
* @param {TreeNode} root
11+
* @return {number}
12+
*/
13+
var maxDepth = function (root) {
14+
// 트리가 비어있는 경우, 깊이는 0
15+
if (!root) return 0;
16+
17+
// 왼쪽 서브트리의 최대 깊이를 재귀적으로 계산
18+
const leftDepth = maxDepth(root.left);
19+
20+
// 오른쪽 서브트리의 최대 깊이를 재귀적으로 계산
21+
const rightDepth = maxDepth(root.right);
22+
23+
// 왼쪽과 오른쪽 중 더 깊은 쪽을 선택하고, 현재 노드를 포함해 +1
24+
return Math.max(leftDepth, rightDepth) + 1;
25+
};

0 commit comments

Comments
 (0)