Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // printLevelOrder (tree)
- // Create an queue and push root node into it
- // when queue is not empty
- // pop a node from the queue and print it
- // push left child of popped node to queue if not null
- // push right child of popped node to queue if not null
- // 40
- // / \
- // 20 60
- // / \ / \
- // 10 30 50 70
- public class BinaryTree {
- public static class TreeNode {
- int data;
- TreeNode left;
- TreeNode right;
- TreeNode (int data) {
- this.data = data;
- }
- }
- void printLevelOrder (TreeNode rootNode) {
- Queue<TreeNode> queue = new LinkedList()<TreeNode>;
- if (rootNode != null )
- queue.add(rootNode);
- else
- return;
- while (!queue.isEmpty()) {
- TreeNode tempNode = queue.poll();
- System.out.printf("%d", tempNode.data);
- if (tempNode.left != null ) {
- queue.add(tempNode.left);
- if (tempNode.right != null ) {
- queue.add(tempNode.right);
- }
- }
- }
- public static void main(String args[]) }
- BinaryTree bTree = new BinaryTree();
- TreeNode rootNode = createBinaryTree();
- System.out.println("Level order traversal: ");
- bTree.printLevelOrder (rootNode);
- }
- public static TreeNode createBinaryTree() {
- TreeNode rootNode = new TreeNode(40);
- TreeNode n20 = new TreeNode(20);
- TreeNode n10 = new TreeNode(10);
- TreeNode n30 = new TreeNode(30);
- TreeNode n40 = new TreeNode(40);
- TreeNode n50 = new TreeNode(50);
- TreeNode n60 = new TreeNode(60);
- TreeNode n70 = new TreeNode(70);
- n40.left = n20;
- n40.right = n60;
- n20.left = n10;
- n20.right = n30;
- n60.left = n50;
- n60.right = n70;
- return rootNode;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement