-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_0104MaximumDepthOfBinaryTree.java
More file actions
80 lines (72 loc) · 2.12 KB
/
_0104MaximumDepthOfBinaryTree.java
File metadata and controls
80 lines (72 loc) · 2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package com.heatwave.leetcode.problems;
import java.util.LinkedList;
import java.util.Queue;
public class _0104MaximumDepthOfBinaryTree {
static class Solution {
public int maxDepth(TreeNode root) {
return findDepth(root, 0);
}
private int findDepth(TreeNode root, int depth) {
if (root == null) {
return depth;
}
return Math.max(findDepth(root.left, depth + 1), findDepth(root.right, depth + 1));
}
}
static class SolutionDFS {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
return Math.max(leftDepth, rightDepth) + 1;
}
}
static class SolutionBFS {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
int ans = 0;
while (!queue.isEmpty()) {
int n = queue.size();
while (n-- > 0) {
TreeNode node = queue.remove();
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}
ans++;
}
return ans;
}
}
static class SolutionBacktrack {
int ans = 0;
int depth = 0;
public int maxDepth(TreeNode root) {
traverse(root);
return ans;
}
public void traverse(TreeNode root) {
if (root == null) {
return;
}
// preorder
depth++;
if (root.left == null && root.right == null) {
ans = Math.max(ans, depth);
}
traverse(root.left);
traverse(root.right);
// postorder
depth--;
}
}
}