Skip to content

Commit 2af5762

Browse files
committed
maximum-depth-of-binary-tree solution
1 parent 95ca7a4 commit 2af5762

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/**
2+
[λ¬Έμ œν’€μ΄]
3+
- μ΅œλŒ€ depth κ΅¬ν•˜κΈ°
4+
- left or right의 null일 λ•Œ depth의 max κ΅¬ν•˜κΈ°
5+
- DFS 1
6+
time: O(N), space: O(N)
7+
class Solution {
8+
public int maxDepth(TreeNode root) {
9+
return nextNode(root, 0);
10+
}
11+
12+
private int nextNode(TreeNode node, int depth) {
13+
if (node == null) {
14+
return depth;
15+
}
16+
17+
int leftDepth = nextNode(node.left, depth + 1);
18+
int rightDepth = nextNode(node.right, depth + 1);
19+
return Math.max(leftDepth, rightDepth);
20+
}
21+
}
22+
- DFS 2
23+
time: O(N), space: O(N)
24+
25+
[회고]
26+
이전에 ν’€μ—ˆλ˜ Merget Two Sorted Lists λ¬Έμ œμ—μ„œ μ£Όμ–΄μ§„ λ©”μ„œλ“œλ₯Ό μž¬μ‚¬μš©ν•  수 μžˆκ² λ‹€λŠ” μƒκ°μœΌλ‘œ ν’€ 수 μžˆμ—ˆλ‹€!
27+
*/
28+
29+
/**
30+
* Definition for a binary tree node.
31+
* public class TreeNode {
32+
* int val;
33+
* TreeNode left;
34+
* TreeNode right;
35+
* TreeNode() {}
36+
* TreeNode(int val) { this.val = val; }
37+
* TreeNode(int val, TreeNode left, TreeNode right) {
38+
* this.val = val;
39+
* this.left = left;
40+
* this.right = right;
41+
* }
42+
* }
43+
*/
44+
class Solution {
45+
public int maxDepth(TreeNode root) {
46+
if (root == null) {
47+
return 0;
48+
}
49+
50+
int leftDepth = maxDepth(root.left);
51+
int rightDepth = maxDepth(root.right);
52+
return Math.max(leftDepth, rightDepth) + 1;
53+
}
54+
}
55+

0 commit comments

Comments
Β (0)