Flipkart Interview Question
SDE-2sCountry: India
Interview Type: Phone Interview
{struct node
{
int value;
struct node* child[5];
};
int n = 5;//maximum number of child nodes
void zigzag(struct node * root)
{
if(root== NULL)
return;
Stack s1;
Stack s2;
int i =0;
s1.push(root)
while(!s1.empty() || !s2.empty())
{
while(!s1.empty())
{
root = s1.pop();
cout<<root->value;
for(i =0;i< n;i++)
if(root->child[i])
s2.push(root->child[i]);
}
if(s1.empty())
cout<<endl; // empty line after every level
while(!s2.empty())
{
root = s2.pop();
cout<<root->value;
for(i =n-1;i> 0;i--)
if(root->child[i])
s1.push(root->child[i])
}
if(s2.empty())
cout<<endl;//// empty line after every level
}
}
}
class static NaryTreeNode<T>{
ArrayList<NaryTreeNode<T>> children;
T value;
public NaryTreeNode<T>(T value){
this.children = new ArrayList<NaryTreeNode<T>>();
this.value = value;
}
}
public static void printZigZag(NaryTreeNode<String> node){
Stack<NaryTreeNode<String>> thisLevel = new Stack<NaryTreeNode<String>>();
Stack<NaryTreeNode<String>> nextLevel = new Stack<NaryTreeNode<String>>();
Stack<NaryTreeNode<String>> temp;
boolean isLeftToRight = false;
StringBuilder line = new StringBuilder();
thisLevel.push(node);
while(!thisLevel.isEmpty()){
while(!thisLevel.isEmpty()){
node = thisLevel.pop();
line.append(node.value);
line.append(' ');
if(isLeftToRight){
for(int i = 0; i < node.children.size(); i++){
nextLevel.push(node.children.get(i));
}
}
else{
for(int i = node.children.size() -1; i > -1; i--){
nextLevel.push(node.children.get(i);
}
}
}
java.lang.System.out.println(line.toString());
line.setLength(0);
temp = thisLevel;
thisLevel = nextLevel;
nextLevel = temp;
isLeftToRight = !isLeftToRight;
}
}
- Vir Pratap Uttam May 10, 2015