Advertisement
Guest User

Untitled

a guest
May 26th, 2015
264
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. // printLevelOrder (tree)
  2. // Create an queue and push root node into it
  3. // when queue is not empty
  4. // pop a node from the queue and print it
  5. // push left child of popped node to queue if not null
  6. // push right child of popped node to queue if not null
  7. // 40
  8. // / \
  9. // 20 60
  10. // / \ / \
  11. // 10 30 50 70
  12.  
  13. public class BinaryTree {
  14.  
  15. public static class TreeNode {
  16. int data;
  17. TreeNode left;
  18. TreeNode right;
  19. TreeNode (int data) {
  20. this.data = data;
  21. }
  22.  
  23.  
  24. }
  25.  
  26. void printLevelOrder (TreeNode rootNode) {
  27.  
  28. Queue<TreeNode> queue = new LinkedList()<TreeNode>;
  29. if (rootNode != null )
  30. queue.add(rootNode);
  31. else
  32. return;
  33.  
  34. while (!queue.isEmpty()) {
  35. TreeNode tempNode = queue.poll();
  36. System.out.printf("%d", tempNode.data);
  37. if (tempNode.left != null ) {
  38. queue.add(tempNode.left);
  39. if (tempNode.right != null ) {
  40. queue.add(tempNode.right);
  41. }
  42. }
  43.  
  44. }
  45.  
  46. public static void main(String args[]) }
  47. BinaryTree bTree = new BinaryTree();
  48.  
  49. TreeNode rootNode = createBinaryTree();
  50. System.out.println("Level order traversal: ");
  51. bTree.printLevelOrder (rootNode);
  52.  
  53. }
  54.  
  55. public static TreeNode createBinaryTree() {
  56.  
  57. TreeNode rootNode = new TreeNode(40);
  58. TreeNode n20 = new TreeNode(20);
  59. TreeNode n10 = new TreeNode(10);
  60. TreeNode n30 = new TreeNode(30);
  61. TreeNode n40 = new TreeNode(40);
  62. TreeNode n50 = new TreeNode(50);
  63. TreeNode n60 = new TreeNode(60);
  64. TreeNode n70 = new TreeNode(70);
  65.  
  66. n40.left = n20;
  67. n40.right = n60;
  68.  
  69. n20.left = n10;
  70. n20.right = n30;
  71.  
  72. n60.left = n50;
  73. n60.right = n70;
  74. return rootNode;
  75. }
  76.  
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement