Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // http://code2begin.blogspot.com
- // program to print given binary tree in spiral level wise traversal
- /**
- * Created by MOHIT on 25-05-2018.
- */
- import java.util.*;
- // node class
- class node{
- int data;
- node left;
- node right;
- // function that returns a pointer to new node
- public node(int element){
- this.data = element;
- this.left = null;
- this.right = null;
- }
- };
- public class BinaryTree {
- // function to print the tree using spiral level wise traversal
- static void spiral_traversal(node root){
- if (root == null){
- return;
- }
- ArrayList STACK1 = new ArrayList<node>();
- ArrayList STACK2 = new ArrayList<node>();
- int level = 1;
- STACK1.add(root);
- while(!STACK1.isEmpty() || !STACK2.isEmpty()){
- System.out.print("\nNodes at level " + level + " are : ");
- level += 1;
- while (!STACK1.isEmpty()){
- // pop the first node from the queue
- node NODE = (node)STACK1.get(0);
- STACK1.remove(0);
- System.out.print(NODE.data + " ");
- // push the left child on queue
- if (NODE.right != null) {
- STACK2.add(NODE.right);
- }
- // push the right child on queue
- if (NODE.left != null) {
- STACK2.add(NODE.left);
- }
- }
- System.out.print("\nNodes at level " + level + " are : ");
- level += 1;
- while (!STACK2.isEmpty()){
- // pop the first node from the queue
- node NODE = (node)STACK2.get(0);
- STACK2.remove(0);
- System.out.print(NODE.data + " ");
- // push the left child on queue
- if (NODE.right != null) {
- STACK1.add(NODE.right);
- }
- // push the right child on queue
- if (NODE.left != null) {
- STACK1.add(NODE.left);
- }
- }
- }
- }
- public static void main(String arg[]) {
- node head = new node(1);
- head.left = new node(2);
- head.right = new node(3);
- head.left.left = new node(4);
- head.left.right = new node(5);
- head.right.right = new node(6);
- head.left.left.right = new node(7);
- head.right.right.left = new node(8);
- head.left.left.right.left = new node(9);
- head.left.left.right.left.left = new node(10);
- head.right.right.left.right = new node(11);
- System.out.print("SPIRAL Level wise traversal of the above binary tree is : ");
- spiral_traversal(head);
- }
- }
Add Comment
Please, Sign In to add comment