Skip to content

Commit 2c75463

Browse files
committed
add: maximum depth of binary tree solution
1 parent 818402e commit 2c75463

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode() {}
8+
* TreeNode(int val) { this.val = val; }
9+
* TreeNode(int val, TreeNode left, TreeNode right) {
10+
* this.val = val;
11+
* this.left = left;
12+
* this.right = right;
13+
* }
14+
* }
15+
*/
16+
17+
18+
class Solution {
19+
/*
20+
time complexity: O(n)
21+
space complexity: O(h)
22+
*/
23+
int maxDepth = 0;
24+
25+
public int maxDepth(TreeNode root) {
26+
depthChk(root, 0);
27+
return maxDepth;
28+
}
29+
30+
public void depthChk(TreeNode node, int depth) {
31+
if (node == null) {
32+
maxDepth = Math.max(depth, maxDepth);
33+
return;
34+
}
35+
36+
// 트리의 좌우 탐색
37+
depthChk(node.left, depth + 1);
38+
depthChk(node.right, depth + 1);
39+
}
40+
}

0 commit comments

Comments
 (0)