Interview Question
Developer Program EngineersCountry: India
This is bst tree.we want to print as the label wise means first on
15
12 23
8 17 20 29
5 9 27 38
I think the problem is a little modification of BFS, what is expected here is that you print all the nodes levelwise...e.g. assume a complete BST with nodes "2 7 9 11 13 16 19", where the order given earlier is the result of inorder traversal..then the output should be
11
7 16
2 9 13 19
where 11 is the root, on next lines its children, 7 and 16, on next line their children etc .. the code given below does that, it
public static void newLevelWise(Node head){
Vector<Node> q = new Vector<Node>();
Node ref1=null;
Node ref2=null;
q.add(null);
q.add(head);
while(q.size()>0){
ref1 = q.remove(0);
if(ref1==null){
if(q.size()==0){
return;
}
ref2=q.remove(0);
System.out.println("");
System.out.print(ref2+" ");
q.add(null);
if(ref2.left!=null){
q.add(ref2.left);
}
if(ref2.right!=null){
q.add(ref2.right);
}
}else{
System.out.print(ref1+" ");
if(ref1.left!=null){
q.add(ref1.left);
}
if(ref1.right!=null){
q.add(ref1.right);
}
}
}
}
// BFSTree.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
struct Tree
{
int data;
Tree *left;
Tree *right;
};
struct linkedList
{
Tree *node;
linkedList *next;
};
Tree * CreateTree(Tree *root, int value)
{
if(root == NULL)
{
root = new Tree();
root->data = value;
root->left = NULL;
root->right = NULL;
}
else if(value < root->data)
root->left = CreateTree(root->left, value);
else
root->right = CreateTree(root->right, value);
return root;
}
void PrintTreeBFS(linkedList *current, linkedList *last)
{
if(current == NULL)
return;
else
{
//printf("\n Node Value %d" + current->node->data);
printf("\n Node Value %d", current->node->data);
if(current->node->left != NULL)
{
linkedList *onemore = new linkedList();
onemore->node = current->node->left;
onemore->next = NULL;
last->next = onemore;
last = last->next;
}
if(current->node->right != NULL)
{
linkedList *another = new linkedList();
another->node = current->node->right;
another->next = NULL;
last->next = another;
last = last->next;
}
current = current->next;
PrintTreeBFS(current, last);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int arr[] = {30,15,10,66,51,53,12};
linkedList *list = new linkedList();
Tree *root = NULL;
for(int i=0; i< 7; i++)
root = CreateTree(root, arr[i]);
list->node = root;
list->next = NULL;
PrintTreeBFS(list, list);
return 0;
}
Can you please explain the question in detail
- DashDash April 12, 2012I am not able to understand what this label is