Last active
May 27, 2018 04:34
-
-
Save thmain/ef612a50d58cb2d164fb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.LinkedList; | |
import java.util.Queue; | |
public class T_TreeSizeWithOutRecursion { | |
// If we are not using recursion then we need a data structure to store the | |
// tree traversal, we will use queue here | |
public static int getSize(Node root) { | |
if (root != null) { | |
int size=0; // size of tree | |
Queue<Node> q = new LinkedList<>(); | |
// add root to the queue | |
q.add(root); | |
while (!q.isEmpty()) { | |
Node x = q.poll(); | |
//increment the size | |
size++; | |
//add children to the queue | |
if(x.left!=null){ | |
q.add(x.left); | |
} | |
if(x.right!=null){ | |
q.add(x.right); | |
} | |
} | |
return size; | |
} | |
// if root is null, return 0 | |
return 0; | |
} | |
public static void main(String[] args) { | |
Node root = new Node(1); | |
root.left = new Node(2); | |
root.right = new Node(3); | |
root.left.left = new Node(4); | |
root.left.right = new Node(5); | |
System.out.println("Tree Size: " + getSize(root)); | |
} | |
} | |
class Node { | |
int data; | |
Node left; | |
Node right; | |
public Node(int data) { | |
this.data = data; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment