-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNumberOfLeaves.java
44 lines (36 loc) · 1.26 KB
/
NumberOfLeaves.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
package com.anudev.ds.trees;
import java.util.LinkedList;
import java.util.Queue;
public class NumberOfLeaves {
public static int findNumberOfLeavesRecursively(Node node) {
if (node == null) {
return 0;
}
if (node.getRightNode() == null && node.getLeftNode() == null) {
return 1;
}
return findNumberOfLeavesRecursively(node.getLeftNode())
+ findNumberOfLeavesRecursively(node.getRightNode());
}
public static int findNumberOfLeavesNonRecursively(Node node) {
int numberOfLeaves = 0;
Queue<Node> queue = new LinkedList<>();
queue.add(node);
while (!queue.isEmpty()) {
Node queueNode = queue.poll();
// check if left and right node are null
if (queueNode.getLeftNode() == null && queueNode.getRightNode() == null) {
numberOfLeaves++;
}
// put right node in queue
if (queueNode.getRightNode() != null) {
queue.add(queueNode.getRightNode());
}
// put left node in queue
if (queueNode.getLeftNode() != null) {
queue.add(queueNode.getLeftNode());
}
}
return numberOfLeaves;
}
}