-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Description
//https://www.geeksforgeeks.org/level-order-traversal-in-spiral-form/
//https://leetcode.com/explore/interview/card/top-interview-questions-medium/108/trees-and-graphs/787/
// Java implementation of an O(n) approach of level order
// traversal in spiral form
import java.util.*;
// A Binary Tree node
class Node
{
int data;
Node left, right;
public Node(int item)
{
data = item;
left = right = null;
}
}
public class BinaryTree
{
static Node root;
void printSpiral(Node node)
{
if(node == null){
return;
}
Stack<Node> one = new Stack<Node>();
Stack<Node> two = new Stack<Node>();
one.push(node);
while(!one.empty() || !two.empty()){
while(!one.empty()){
Node oneTemp = one.peek();
one.pop();
if(oneTemp != null){
System.out.println(oneTemp.data);
if(oneTemp.right != null){
two.push(oneTemp.right);
}
if(oneTemp.left != null){
two.push(oneTemp.left);
}
}
}
while(!two.empty()){
Node twoTemp = two.peek();
two.pop();
System.out.println(twoTemp.data);
if(twoTemp != null){
if(twoTemp.left != null){
one.push(twoTemp.left);
}
if(twoTemp.left != null){
one.push(twoTemp.right);
}
}
}
}
}
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(7);
tree.root.left.right = new Node(6);
tree.root.right.left = new Node(5);
tree.root.right.right = new Node(4);
System.out.println("Spiral Order traversal of Binary Tree is ");
tree.printSpiral(root);
}
}
// This code has been contributed by Mayank Jaiswal(mayank_24)
Metadata
Metadata
Assignees
Labels
No labels