public class CalculateSizeUsingWithoutRecusrion {
public static void main(String args[]) {
Node rootNode = new Node("4");
rootNode.left = new Node("2");
rootNode.left.left = new Node("1");
rootNode.left.left.left = new Node("9");
rootNode.left.right = new Node("3");
rootNode.right = new Node("6");
rootNode.right.right = new Node("7");
rootNode.right.left = new Node("5");
rootNode.right.right.right = new Node("8");
System.out.println(calcSize(rootNode));
}
static int calcSize(Node node) {
Queue<Node> queue = new LinkedBlockingQueue<>();
queue.add(node);
int count = 0;
while(!queue.isEmpty()) {
Node node1 = queue.remove();
count= count+1;
if(null!=node1.left) {
queue.add(node1.left);
}
if(null!=node1.right) {
queue.add(node1.right);
}
}
return count;
}
}
class BinayTree{
static class Node{
String value;
Node left;
Node right;
Node(String val){
value = val;
left = right = null;
}
}
}
output:9
public static void main(String args[]) {
Node rootNode = new Node("4");
rootNode.left = new Node("2");
rootNode.left.left = new Node("1");
rootNode.left.left.left = new Node("9");
rootNode.left.right = new Node("3");
rootNode.right = new Node("6");
rootNode.right.right = new Node("7");
rootNode.right.left = new Node("5");
rootNode.right.right.right = new Node("8");
System.out.println(calcSize(rootNode));
}
static int calcSize(Node node) {
Queue<Node> queue = new LinkedBlockingQueue<>();
queue.add(node);
int count = 0;
while(!queue.isEmpty()) {
Node node1 = queue.remove();
count= count+1;
if(null!=node1.left) {
queue.add(node1.left);
}
if(null!=node1.right) {
queue.add(node1.right);
}
}
return count;
}
}
class BinayTree{
static class Node{
String value;
Node left;
Node right;
Node(String val){
value = val;
left = right = null;
}
}
}
output:9
No comments:
Post a Comment