-
-
Notifications
You must be signed in to change notification settings - Fork 164
/
Copy pathMaxDepthBinaryTree.java
80 lines (63 loc) · 2.18 KB
/
MaxDepthBinaryTree.java
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 java1.algorithms.tree;
import java.util.*;
public class MaxDepthBinaryTree {
// Recursive DFS:- TC: O(n) SC: O(n)
private static int maxDepth1(TreeNode root) {
if(root == null) return 0;
return 1 + Math.max(maxDepth1(root.left), maxDepth1(root.right));
}
// Iterative DFS using two stacks:- TC: O(n) SC: O(n)
private static int maxDepth2(TreeNode root) {
if(root == null) return 0;
Stack<TreeNode> stack = new Stack<>();
Stack<Integer> layer = new Stack<>();
stack.push(root);
layer.push(1);
int maxDepth = 0;
while(!stack.isEmpty()) {
TreeNode node = stack.pop();
int temp = layer.pop();
maxDepth = Math.max(maxDepth, temp);
if(node.left != null) {
stack.push(node.left);
layer.push(temp + 1);
}
if(node.right != null) {
stack.push(node.right);
layer.push(temp + 1);
}
}
return maxDepth;
}
//BFS:- TC: O(n) SC: O(n)
private static int maxDepth3(TreeNode root) {
if(root == null) return 0;
int count = 0;
//Queue is used to keep all the nodes to be traversed
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
//Traverse the tree by layer
for(int i=0; i<size; i++) {
TreeNode node = queue.poll();
if(node.left != null) queue.offer(node.left);
if(node.right != null) queue.offer(node.right);
}
count++;
}
return count;
}
public static void main(String[] args) {
TreeNode root = new TreeNode(0);
root.left = new TreeNode(1);
root.right = new TreeNode(2);
root.left.left = new TreeNode(3);
root.left.right = new TreeNode(4);
root.right.left = new TreeNode(5);
root.right.right = new TreeNode(6);
System.out.println(maxDepth1(root));
System.out.println(maxDepth2(root));
System.out.println(maxDepth3(root));
}
}