473,395 Members | 1,670 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

use queue to Level traverse a tree

18
Following is my logic to traverse level by level an mway search tree....

(Yeah I finally used templates to implement a queue... :) )

void mWayTree:: TraverseLevelOrder(Node *root,int lvl)
{
int i;
int level;
Dq<Node *> Q;
Node *tmp;
Node *tmpPush,*tmpPop;
tmp = new Node(mway);
tmpPop = new Node(mway);

if(root != NULL)
{
level = lvl;
Q.Add(root);
while(!Q.IsEmpty())
{

tmp = Q.First();
//Visit keys in first node
cout<<"\nKeys at level "<<level++<<":";
for(i = 0; i < tmp->noofKeys; i++)
{
cout<<tmp->keys[i]<<",";
}
//Push children of node at rear of queue;
//TODO check logic to increment level number
for(i = 0; i< tmp->noofKeys + 1 ; i++)
{
tmpPush = new Node(mway);
if(tmp->childPointer[i] != NULL)
{
tmpPush = tmp->childPointer[i];
//Q.Add(tmpPush);
TraverseLevelOrder(tmpPush,level);
}

}

//Delete first visited node from queue
Q.Delete(tmpPop);

}
}
}

The code for queue is :

template<class T>
class QNode{ //Node in the queue which will contain one BTree node as data
public:
T data;
QNode<T> *link;
};

template<class T>
class Dq { //Queue manager class to add and delete elements from queue
public:
Dq() {front = rear = NULL;}
~Dq();
bool IsEmpty() const
{return ((front==NULL) ? true: false);}
T First() const;
Dq<T>& Add(const T& x);
Dq<T>& Delete(T& x);
private:
QNode<T> *front;
QNode<T> *rear;
};

template <class T>
Dq<T>::~Dq()
{
//Delete all nodes in queue
QNode<T> *next;
while (front) {
next = front->link;
delete front;
front = next;
}
}


template<class T>
T Dq<T>::First() const
{
// Get first element of queue.
if (!IsEmpty())
{
return front->data;
}
}

template<class T>
Dq<T>& Dq<T>::Add(const T& x)
{
// Add x to rear of queue.
// create QNode for new element x
QNode<T> *p = new QNode<T>;
p->data = x;
p->link = NULL;

// add new QNode to rear of queue
if (front) rear->link = p; // if(not empty)
else front = p; // if(empty)
rear = p;

return *this;
}

template<class T>
Dq<T>& Dq<T>::Delete(T& x)
{
// Delete first element if queue is non empty and put it in x.
if (!IsEmpty())
{
// save element in first node
x = front->data;

// delete first node
QNode<T> *p = front;
front = front->link;
delete p;

return *this;
}
}

Now the problem here is that :

When actually tree is like :

4
2 6,8
1 3 5 7 9

Now acc to above level traverse method output is :

Keys at level 0 : 4
Keys at level 1: 2
Keys at level 2: 1
Keys at level 2: 3
Keys at level 1: 6,8
Keys at level 2: 5
Keys at level 2: 7
Keys at level 2: 9

This output format which I think does not really look like a level order traversal which I really want....

I want to show out put this way:

Key at level 0 : 4
Keys at level 1: 2,6,8
Keys at level 2: 1,3,5,7,9

I know there is something logically wrong in above code...But I can not find where? Or is this approach correct?
Oct 25 '09 #1
6 4396
newb16
687 512MB
Let's suppose you just printed node '2' and want to skip to next node on this level instead of printing its children. You need to provide an additional argument to Traverse() function so that it will print only nodes with given level and won't traverse deeper than this level, and then call it for all levels (stop when there are no nodes at some level)
Oct 25 '09 #2
gskbond
18
I still did not get what you are trying to say....this is supposed to be a recursive algorithm......and I cant figure out whether there is a way to find out which nodes are at same level....any other suggestions?
Oct 25 '09 #3
gskbond
18
Hello any other advise??? I did not get above advise...please reply
Oct 26 '09 #4
newb16
687 512MB
Add one more parameter to your traverse function (displaylevel), and print the data only if current level is equal to displaylevel. Make the function return false if nothing is printed for this node or any of its children. Then in main program loop with increasing displaylevel until function returns false.
Oct 26 '09 #5
gskbond
18
I used following code:

bool BTree::AnotherTraverseLevelOrder(Node *root,int lvl,int displaylevel)
{
int i;
int level;
Dq<Node *> Q;
Node *tmp;
Node *tmpPush,*tmpPop;
tmp = new Node(mway);
tmpPop = new Node(mway);

if(root != NULL)
{
level = lvl;
Q.Add(root);
while(!Q.IsEmpty())
{

tmp = Q.First();
//Visit keys in first node
if(level == displaylevel)
{
cout<<"\nKeys at level "<<level + 1<<":";
for(i = 0; i < tmp->noofKeys; i++)
{
cout<<tmp->keys[i]<<",";
}
}
else return false;
//Push children of node at rear of queue;
//TODO check logic to increment level number
for(i = 0; i< tmp->noofKeys + 1 ; i++)
{
tmpPush = new Node(mway);
if(tmp->childPointer[i] != NULL)
{
tmpPush = tmp->childPointer[i];
//Q.Add(tmpPush);
AnotherTraverseLevelOrder(tmpPush,level+1,level+1) ;
}
else level++;
}

//Delete first visited node from queue
Q.Delete(tmp);
if(Q.IsEmpty()) return false;
}
}
return false;
}

int main(int argc,char* argv[])
{

mWayTree myTree(3);
myTree.Insert(1);
myTree.Insert(2);
myTree.Insert(3);
myTree.Insert(4);
myTree.Insert(5);
myTree.Insert(6);
myTree.Insert(7);
myTree.Insert(8);
myTree.Insert(9);
int i=0;
bool falseIndicator = true;

for(i=0; falseIndicator != false; i++)
falseIndicator = myTree.AnotherTraverseLevelOrder(myTree.root,0,i);

getchar();
return 1;
}


But still it is giving out put in same format :
Keys at level 1 : 4
Keys at level 2: 2
Keys at level 3: 1
Keys at level 4: 3
Keys at level 2: 6,8
Keys at level 3: 5
Keys at level 3: 7
Keys at level 3: 9

Please help....its not working
Oct 27 '09 #6
newb16
687 512MB
AnotherTraverseLevelOrder(tmpPush,level+1,level+1) ;

this is wrong. Why is it setting displaylevel to current level?

To debug, try first to run the function for some level , e.g. 2 and ensure it works for it. Then add loop by level.
Oct 27 '09 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

17
by: Bart Nessux | last post by:
How can one view the contents of a queue? I'd like to verify that the queue has the same number of objects as the list that has been put into it. Also, should one think of a queue as static or...
18
by: Shannon Jacobs | last post by:
Trying to solve this with a regex approach rather than the programmatic approach of counting up and down the levels. I have a fairly complicated HTML page that I want to simplify. I've been able to...
38
by: Aaron W. LaFramboise | last post by:
Hello, I understand that an easy way to make the standard std::priority_queue stable is by including an integer stamp with each node that is incremented each time a new node is pushed into the...
3
by: Amit | last post by:
Greetings All. One of the usages that I need is accessing the contents of the container that I am using in level order( which would mean breadth- first search approach for a binary tree) as...
4
by: negative | last post by:
Dear all, I want to create a tree, where every node has an undetermined number of children (during the population of the tree, the exact number of children of each node , will become clear). So...
5
by: Manish | last post by:
This is the print_r() for a variable $categories. $categories :: Array ( =Array ( =Array (
1
by: ericstein81 | last post by:
I need to traverse a binary search tree and be able to give an output of how many leaf nodes there are, and how many leafs have one child and how many leafs have two children. Im not asking for a...
1
by: Brij kishor | last post by:
In java, how can we traverse a binary search tree level by level ?
4
by: gskbond | last post by:
Below is the node for m way tree class Node { public: Node(int imway); ~Node(); int noofKeys; int *keys; Node **childPointer;
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.