Last active
December 16, 2017 07:01
-
-
Save rishi93/3cefa6cbf98a253739132afaa43212c7 to your computer and use it in GitHub Desktop.
Binary Tree Level Order Traversal
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); | |
| while(queue.isEmpty() == false){ | |
| Node current = queue.poll(); | |
| System.out.print(current.data + " "); | |
| if(current.left != null){ | |
| queue.add(current.left); | |
| } | |
| if(current.right != null){ | |
| queue.add(current.right); | |
| } | |
| } | |
| 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); | |
| System.out.println("Level order traversal of the tree is:"); | |
| tree.printLevelOrder(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment