Guest User

Untitled

a guest
Nov 14th, 2018
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.94 KB | None | 0 0
  1. // Java implementation of a O(n) time
  2. // method for Zigzag order traversal
  3. import java.util.*;
  4.  
  5. // Binary Tree node
  6. class Node
  7. {
  8. int data;
  9. Node leftChild;
  10. Node rightChild;
  11. Node(int data)
  12. {
  13. this.data = data;
  14. }
  15. }
  16.  
  17. class BinaryTree {
  18. Node rootNode;
  19.  
  20. // function to print the
  21. // zigzag traversal
  22. void printZigZagTraversal() {
  23.  
  24. // if null then return
  25. if (rootNode == null) {
  26. return;
  27. }
  28.  
  29. // declare two stacks
  30. Stack<Node> currentLevel = new Stack<>();
  31. Stack<Node> nextLevel = new Stack<>();
  32.  
  33. // push the root
  34. currentLevel.push(rootNode);
  35. boolean leftToRight = true;
  36.  
  37. // check if stack is empty
  38. while (!currentLevel.isEmpty()) {
  39.  
  40. // pop out of stack
  41. Node node = currentLevel.pop();
  42.  
  43. // print the data in it
  44. System.out.print(node.data + " ");
  45.  
  46. // store data according to current
  47. // order.
  48. if (leftToRight) {
  49. if (node.leftChild != null) {
  50. nextLevel.push(node.leftChild);
  51. }
  52.  
  53. if (node.rightChild != null) {
  54. nextLevel.push(node.rightChild);
  55. }
  56. }
  57. else {
  58. if (node.rightChild != null) {
  59. nextLevel.push(node.rightChild);
  60. }
  61.  
  62. if (node.leftChild != null) {
  63. nextLevel.push(node.leftChild);
  64. }
  65. }
  66.  
  67. if (currentLevel.isEmpty()) {
  68. leftToRight = !leftToRight;
  69. Stack<Node> temp = currentLevel;
  70. currentLevel = nextLevel;
  71. nextLevel = temp;
  72. }
  73. }
  74. }
  75. }
  76.  
  77. public class zigZagTreeTraversal {
  78.  
  79. // driver program to test the above function
  80. public static void main(String[] args)
  81. {
  82. BinaryTree tree = new BinaryTree();
  83. tree.rootNode = new Node(1);
  84. tree.rootNode.leftChild = new Node(2);
  85. tree.rootNode.rightChild = new Node(3);
  86. tree.rootNode.leftChild.leftChild = new Node(7);
  87. tree.rootNode.leftChild.rightChild = new Node(6);
  88. tree.rootNode.rightChild.leftChild = new Node(5);
  89. tree.rootNode.rightChild.rightChild = new Node(4);
  90.  
  91. System.out.println("ZigZag Order traversal of binary tree is");
  92. tree.printZigZagTraversal();
  93. }
  94. }
  95.  
  96. // This Code is contributed by Harikrishnan Rajan.
Add Comment
Please, Sign In to add comment