-
Notifications
You must be signed in to change notification settings - Fork 0
/
33. 104. Maximum Depth of Binary Tree
96 lines (78 loc) · 2.2 KB
/
33. 104. Maximum Depth of Binary Tree
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
95
96
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
//Here I Write 3 Approach - most famous (recursive)
//recursive approach
//return recursive(root);
//bfs approach (Level Order Traversal)
//return bfs(root);
//dfs Iterative
return dfsIterative(root);
}
private int dfsIterative(TreeNode root){
if(root==null){
return 0;
}
Stack<TreeNode> st = new Stack<TreeNode>();
Stack<Integer> depth = new Stack<Integer>();
int maxDepth = 0;
st.push(root);
depth.push(1);
while(!st.isEmpty()){
TreeNode node = st.pop();
int currDepth = depth.pop();
maxDepth = Math.max(maxDepth,currDepth);
if(node.right!=null){
st.push(node.right);
depth.push(currDepth+1);
}
if(node.left!=null){
st.push(node.left);
depth.push(currDepth+1);
}
}
return maxDepth;
}
private int recursive(TreeNode root){
if(root==null){
return 0;
}
return 1+Math.max(recursive(root.left),recursive(root.right));
}
private int bfs(TreeNode root){
if(root==null){
return 0;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
int maxDepth = 0;
queue.add(root);
while(!queue.isEmpty()){
maxDepth++;
int levelSize = queue.size();
for(int i=0;i<levelSize;i++){
TreeNode node = queue.poll();
if(node.left!=null){
queue.add(node.left);
}
if(node.right!=null){
queue.add(node.right);
}
}
}
return maxDepth;
}
}