-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDeepestNode.java
More file actions
39 lines (32 loc) · 823 Bytes
/
Copy pathDeepestNode.java
File metadata and controls
39 lines (32 loc) · 823 Bytes
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
// Algorithm to find the deepest node of the binary tree
// Time Complexity - O(n)
// Space Complexity - O(n)
// Problem 14
import java.util.LinkedList;
import java.util.Queue;
public class DeepestNode {
public static Node DeepestNode(Node root) {
Node current, temp = null;
Queue<Node> queue = new LinkedList<Node>();
if(root == null) {
return null;
}
current = root;
queue.add(current);
// The last element in the queue is the deepest element
while(!queue.isEmpty()) {
temp = queue.poll();
if(temp.left != null) {
queue.add(temp.left);
}
if(temp.right != null) {
queue.add(temp.right);
}
}
return temp;
}
public static void main(String[] args) {
BinaryTree binaryTree = new BinaryTree();
System.out.println(DeepestNode(binaryTree.BinaryTree2()).data);
}
}