File tree Expand file tree Collapse file tree 1 file changed +55
-0
lines changed
maximum-depth-of-binary-tree Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Original file line number Diff line number Diff line change
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
+
You canβt perform that action at this time.
0 commit comments