Skip to content

Commit 1b8bfda

Browse files
committed
solve maximum-depth-of-binary-tree
1 parent af050a4 commit 1b8bfda

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
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+
function maxDepth(root: TreeNode | null): number {
16+
// DFS (혹은 BFS) 후 깊이 체크하기
17+
if (!root) return 0;
18+
19+
const stack: [TreeNode, number][] = [[root, 1]];
20+
let maxDepth = 0;
21+
22+
while (stack.length > 0) {
23+
const [node, depth] = stack.pop()!;
24+
maxDepth = Math.max(maxDepth, depth);
25+
26+
if (node.right) {
27+
stack.push([node.right, depth + 1]);
28+
}
29+
if (node.left) {
30+
stack.push([node.left, depth + 1]);
31+
}
32+
}
33+
34+
return maxDepth;
35+
};

0 commit comments

Comments
 (0)