-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFullNode.java
More file actions
52 lines (40 loc) · 1.13 KB
/
Copy pathFullNode.java
File metadata and controls
52 lines (40 loc) · 1.13 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
// Find the number of full nodes in the binary tree
// Problem 17
import java.util.LinkedList;
import java.util.Queue;
public class FullNode {
// Iterative method to get the number of full nodes
public static int NumberOfNodes(Node root) {
Node current = null;
int count = 0;
Queue<Node> queue = new LinkedList<Node>();
if(root != null)
queue.add(root);
while(!queue.isEmpty()) {
current = queue.poll();
if((current.left != null) && (current.right != null)) {
count++;
queue.add(current.left);
queue.add(current.right);
}
else {
if(current.left != null)
queue.add(current.left);
if(current.right != null)
queue.add(current.right);
}
}
return count;
}
// Recursive method to get hte number of full nodes
public static int NumberOfNodesRecursively(Node root) {
if((root.left != null) && (root.right != null)) {
return 1 + NumberOfNodes(root.left) + NumberOfNodes(root.right);
}
return 0;
}
public static void main(String[] args) {
BinaryTree binaryTree = new BinaryTree();
System.out.println(NumberOfNodesRecursively(binaryTree.BinaryTree3()));
}
}