Created
December 16, 2017 08:15
-
-
Save rishi93/9694f7f95bc3da340e1a29af5ac35737 to your computer and use it in GitHub Desktop.
Binary Tree Level order Traversal (Each level on new line)
This file contains hidden or 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.Queue; | |
| import java.util.LinkedList; | |
| class Node{ | |
| int data; | |
| Node left, right; | |
| Node(int data){ | |
| this.data = data; | |
| this.left = null; | |
| this.right = null; | |
| } | |
| } | |
| class BinaryTree{ | |
| Node root; | |
| void printLevelOrder(){ | |
| Queue<Node> queue = new LinkedList<Node>(); | |
| queue.add(root); | |
| int nodeCount; | |
| while(true){ | |
| /* Get the number of nodes in this level */ | |
| nodeCount = queue.size(); | |
| if(nodeCount == 0){ | |
| break; | |
| } | |
| /* Print all the nodes on this level */ | |
| while(nodeCount > 0){ | |
| Node curr = queue.poll(); | |
| System.out.print(curr.data + " "); | |
| nodeCount -= 1; | |
| if(curr.left != null){ | |
| queue.add(curr.left); | |
| } | |
| if(curr.right != null){ | |
| queue.add(curr.right); | |
| } | |
| } | |
| /* Print the new line */ | |
| System.out.println(); | |
| } | |
| } | |
| } | |
| public class Test{ | |
| public static void main(String[] args){ | |
| BinaryTree tree = new BinaryTree(); | |
| tree.root = new Node(1); | |
| tree.root.left = new Node(2); | |
| tree.root.right = new Node(3); | |
| tree.root.left.left = new Node(4); | |
| tree.root.left.right = new Node(5); | |
| tree.root.right.left = new Node(6); | |
| tree.root.right.right = new Node(7); | |
| System.out.println("Level order traversal of the tree:"); | |
| tree.printLevelOrder(); | |
| System.out.println(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment