Skip to content

Commit c865f92

Browse files
refactor 104
1 parent e27fd20 commit c865f92

File tree

1 file changed

+39
-58
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+39
-58
lines changed

src/main/java/com/fishercoder/solutions/_104.java

Lines changed: 39 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -4,70 +4,51 @@
44

55
import java.util.LinkedList;
66

7-
/**
8-
* 104. Maximum Depth of Binary Tree
9-
*
10-
* Given a binary tree, find its maximum depth.
11-
* The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
12-
*
13-
* Note: A leaf is a node with no children.
14-
*
15-
* Example:
16-
* Given binary tree [3,9,20,null,null,15,7],
17-
*
18-
* 3
19-
* / \
20-
* 9 20
21-
* / \
22-
* 15 7
23-
*
24-
* return its depth = 3.
25-
*/
267
public class _104 {
278

28-
public static class Solution1 {
29-
/**
30-
* Recursive solution:
31-
* Time: O(n)
32-
* Space: O(n)
33-
*/
34-
public int maxDepth(TreeNode root) {
35-
if (root == null) {
36-
return 0;
37-
}
38-
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
9+
public static class Solution1 {
10+
/**
11+
* Recursive solution:
12+
* Time: O(n)
13+
* Space: O(n)
14+
*/
15+
public int maxDepth(TreeNode root) {
16+
if (root == null) {
17+
return 0;
18+
}
19+
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
20+
}
3921
}
40-
}
4122

42-
public static class Solution2 {
43-
/**
44-
* Iterative solution:
45-
* Time: O(n)
46-
* Space: O(n)
47-
*/
48-
public int maxDepth(TreeNode root) {
49-
if (root == null) {
50-
return 0;
51-
}
52-
LinkedList<TreeNode> stack = new LinkedList<>();
53-
LinkedList<Integer> depths = new LinkedList<>();
54-
stack.add(root);
55-
depths.add(1);
23+
public static class Solution2 {
24+
/**
25+
* Iterative solution:
26+
* Time: O(n)
27+
* Space: O(n)
28+
*/
29+
public int maxDepth(TreeNode root) {
30+
if (root == null) {
31+
return 0;
32+
}
33+
LinkedList<TreeNode> stack = new LinkedList<>();
34+
LinkedList<Integer> depths = new LinkedList<>();
35+
stack.add(root);
36+
depths.add(1);
5637

57-
int depth = 0;
58-
while (!stack.isEmpty()) {
59-
TreeNode currentNode = stack.pollLast();
60-
int currentDepth = depths.pollLast();
61-
if (currentNode != null) {
62-
depth = Math.max(depth, currentDepth);
63-
stack.add(currentNode.right);
64-
depths.add(currentDepth + 1);
65-
stack.add(currentNode.left);
66-
depths.add(currentDepth + 1);
38+
int depth = 0;
39+
while (!stack.isEmpty()) {
40+
TreeNode currentNode = stack.pollLast();
41+
int currentDepth = depths.pollLast();
42+
if (currentNode != null) {
43+
depth = Math.max(depth, currentDepth);
44+
stack.add(currentNode.right);
45+
depths.add(currentDepth + 1);
46+
stack.add(currentNode.left);
47+
depths.add(currentDepth + 1);
48+
}
49+
}
50+
return depth;
6751
}
68-
}
69-
return depth;
7052
}
71-
}
7253

7354
}

0 commit comments

Comments
 (0)