-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path104.java
More file actions
90 lines (82 loc) · 2.21 KB
/
104.java
File metadata and controls
90 lines (82 loc) · 2.21 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
81
82
83
84
85
86
87
88
89
90
import java.util.LinkedList;
import javafx.util.Pair;
import searchRangeInBinarySearchTree.TreeNode;
//Definition for a binary tree node.
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
// DFS
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
LinkedList<Pair<TreeNode, Integer>> list = new LinkedList<>();
list.add(new Pair(root, 1));
int depth = 0;
while (!list.isEmpty()) {
Pair<TreeNode, Integer> p = list.poll();
TreeNode node = p.getKey();
int v=p.getValue();
depth = Math.max(depth, v);
if (node.left != null) {
list.add(new Pair(node.left, depth+1));
}
if (node.right != null) {
list.add(new Pair(node.right, depth+1));
}
}
return depth;
}
}
// BFS
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
LinkedList<TreeNode> list = new LinkedList<>();
list.add(root);
int depth = 0;
while (!list.isEmpty()) {
depth++;
int size = list.size();//must be like this ,no like for(int i=0;i<list,size()....)
for (int i = 0; i < size; i++) {
TreeNode node = list.poll();
if (node.left != null) {
list.add(node.left);
}
if (node.right != null) {
list.add(node.right);
}
}
}
return depth;
}
}
// recursion
class Solution {
public int maxDepth(TreeNode root) {
return maxDepthR(root, 0);
}
public int maxDepthR(TreeNode root, int sum) {
if (root == null) {
return sum;
}
sum++;
int leftH = maxDepthR(root.left, sum);
int rightH = maxDepthR(root.right, sum);
return Math.max(leftH, rightH);
}
}
//recusion optimize
class Solution {
public int maxDepth(TreeNode root) {
return (root==null)?0:(Math.max(maxDepth(root.left), maxDepth(root.right))+1);
}
}