Psuedocode for spiral level order traversal of a binary tree.
//Define two stacks S1, S2
//At each level,
// S1 carries the nodes to be traversed in that level
// S2 carries the child nodes of the nodes in S1
spiralLevelOrder(root) {
S1 = new Stack()
S2 = new Stack()
S1.push(root)
spiralLevelOrderRecursion(S1, S2, 1)
}
spiralLevelOrderRecursion(S1, S2, level) {
while(S1 not empty) {
node = S1.pop()
visit(node)
if (level is odd) {
S2.push(node.rightNode)
S2.push(node.leftNode)
}
else {
S2.push(node.leftNode)
S2.push(node.rightNode)
}
}
if (S2 not empty)
spiralLevelOrderRecursion(S2, S1, level+1)
}
Sample tree : 1-(2-(4,5),3-(5,6))
format : root-(leftchild, rightchild)
Applying the pseudocode :
spiralLevelOrderRecursion([1], [], 1)
S2 - [] -> [3] -> [2, 3]
visit order : 1
spiralLevelOrderRecursion([2,3], [], 2)
S2 - [] -> [4] -> [5,4] -> [6, 5, 4] -> [7, 6, 5, 4]
visit order : 2, 3
spiralLevelOrderRecursion([7,6,5,4], [], 3)
visit order : 7, 6, 5, 4