-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMAXDepth_BTree.java
More file actions
97 lines (82 loc) · 2.42 KB
/
MAXDepth_BTree.java
File metadata and controls
97 lines (82 loc) · 2.42 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
91
92
93
94
/*
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node
*/
/*
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
/*Solution 1: recursive, O(n)*/
public class Solution {
public int maxDepth(TreeNode root) {
if(root == null)
return 0;
return getDepth(root, 1);
}
public int getDepth(TreeNode node, int depth){
int right=depth; int left=depth;
if(node.left != null)
left = getDepth(node.left, depth+1);
if(node.right != null)
right = getDepth(node.right, depth+1);
return right > left ? right:left;
}
}
/* The following solutions comes from Github ID: walnutown.
/* Simplify solution 1*/
public class Solution {
public int maxDepth(TreeNode root) {
if(root == null)
return 0;
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
}
/*Solution 2: */
// DFS, traverse all the leaf nodes and find the max
// time: O(n)
public class Solution {
public int maxDepth(TreeNode root) {
if (root==null) return 0;
int[] max = new int[1];
finder(root, 1, max); // notice the initial len is 1
return max[0];
}
public void finder(TreeNode root, int len, int[] max){
if (root.left==null && root.right==null){
max[0] = Math.max(len, max[0]);
return;
}
if (root.left != null) finder(root.left, len+1, max);
if (root.right != null) finder(root.right, len+1, max);
}
}
/*Solution 3: */
// BFS, level order traversal
// time: O(n)
public class Solution {
public int maxDepth(TreeNode root) {
if (root == null) return 0;
ArrayList<TreeNode> prev = new ArrayList<TreeNode>();
prev.add(root);
int dep = 1;
while (!prev.isEmpty()){
ArrayList<TreeNode> curr = new ArrayList<TreeNode>();
for (TreeNode node:prev){
if (node.left!=null)
curr.add(node.left);
if (node.right!=null)
curr.add(node.right);
}
if (curr.isEmpty())
break;
prev = curr;
dep++;
}
return dep;
}
}