Yatra.com Interview Question Developer Program Engineers
0of 0 votestravel the tree vertically like
2
3 4
5 6 7 8
output:5 3 2 6 7 4 8
Country: India
Interview Type: In-Person
Do inorder Tree traversal, at each instance push root into stack.
When root becomes null print stack.
tree_traverse(node* root)
{
if(root == null && stack!= empty)
{
print stack
return;
}
s.push(root.value);
tree_traverse(root->left);
tree_traverse(root->right);
}
Won't work. Lets say you have pushed 2,3 &5.
Now the root becomes NULL, print it & return. However you are not emptying the stack.So, 2,3 remains in stack & again you push 6 to stack. The root becomes NULL in next call. You print 6,3,2.
In simple, you have written the program to print all leaf to root paths.
When you print stack you have to pop all the elements to get the element. Do you have an implementation of stack which allows you to traverse it without popping? :) It becomes List if you can traverse.
Here is the function:
void printV(struct node *root,int *arr,int *depth)
{
if(root)
{
arr[++(*depth)]=root->data;
printV(root->left,arr,depth);
if(!(root->left || root->right))
{
while((*depth)>=0)
printf("%d ",arr[(*depth)--]);
}
printV(root->right,arr,depth);
}
}
Complete code: ideone.com/IAKcD
correct me where i am wrong .........i am trying to do is in O(n).....but is in O(nlgn)
int breath_left(struct node* Root)
{
if(!Root)
return 0;
return max(breath_left(Root->left)+1,breath_left(Root->right)-1);
}
int breath_right(struct node* Root)
{
if(!Root)
return 0;
return max(breath_right(Root->right)+1,breath_right(Root->left)-1);
}
int breath(struct node* Root)
{
return (breath_left(root)+breath_right(root)-1);
}
void verticalAtLevel(struct node* Root,int level)
{
if(!Root)
return;
if(level==1)
printf("%d ",Root->data);
verticalAtLevel(Root->left,level-1);
verticalAtLevel(Root->right,level+1);
}
void vertical_travers(struct node* Root)
{
int breathLeft=breath_left(Root);
int i=0;
for(i=breathLeft;i>=(-breath_right(Root));i--){
verticalAtLevel(Root,i);
printf("\n");}
}
Pre-order tree traversal
public class Node {
private Node right;
private Node left;
private int nodeValue;
public Node ( )
{
// a Java constructor
}
public Node leftNode() {return left;}
public Node rightNode() {return right;}
public int getNodeValue() {return nodeValue;}
}
void preOrder (Node root)
{
if(root == null) return;
root.printNodeValue();
preOrder( root.leftNode() );
preOrder( root.rightNode() );
}

What is the question? Please elaborate
- loveCoding on July 04, 2012 Edit | Flag Reply