-
Notifications
You must be signed in to change notification settings - Fork 1
/
02.MinDepthOfBinaryTreeUsingIteration.java
49 lines (41 loc) · 1.16 KB
/
02.MinDepthOfBinaryTreeUsingIteration.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
Class MinimumDepthOfaBinaryTree{
// A binary Tree node
static class Node{
int data;
Node left, right;
}
static class NodeDepth{
Node node;
int depth;
public NodeDepth(Node node, int depth){
this.node = node;
this.depth = depth;
}
}
static int minDepth(Node root){
if (root == null)
return 0;
Queue<NodeDepth> nodes = new LinkedList<>();
NodeDepth nodeDepthPair = new NodeDepth(root, 1);
nodes.add(nodeDepthPair);
while (nodes.isEmpty() == false){
nodeDepthPair = q.peek();
nodes.remove(); //take each node from the queue
Node curNode = nodeDepthPair.node;
int curDepth = nodeDepthPair.depth;
if (curNode.left == null && curNode.right == null)
return curDepth;
if (curNode.left != null){
nodeDepthPair.node = curNode.left;
nodeDepthPair.depth = curDepth + 1;
nodes.add(qi);
}
if (curNode.right != null){
nodeDepthPair.node = curNode.right;
nodeDepthPair.depth = curDepth + 1;
nodes.add(nodeDepthPair);
}
}
return 0;
}
}