473,789 Members | 2,806 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Binary tree Algorithm

Hello!
This is my problem.
I'm trying to make an inorder traversal algorithm for
a binary tree, not a recursive one, but using a stack.
Till now I got this:

void traverse(tree * p)
{
l: if(p==0) goto s;
push(p);
p=p->l; goto l;
r: visit(p);
p=p->r;
goto l;
s: if(top==0) goto x;
p=pop(); goto r;
x: ;
}

we call this function this way : traverse(root);
My question is :
how can I eliminate goto's?
Everything I've tryed is a mess.
I'll be greatfull if you help me.


Dec 3 '05 #1
10 7273

"Aris" <na******@hotma il.com> wrote in message
news:dm******** **@usenet.otene t.gr...
Hello!
This is my problem.
I'm trying to make an inorder traversal algorithm for
a binary tree, not a recursive one, but using a stack.
Till now I got this:

void traverse(tree * p)
{
l: if(p==0) goto s;
push(p);
p=p->l; goto l;
r: visit(p);
p=p->r;
goto l;
s: if(top==0) goto x;
p=pop(); goto r;
x: ;
}

we call this function this way : traverse(root);
My question is :
how can I eliminate goto's?


do
{
while(p)
{
push(p);
p=p->l;
}

if(top)
{
p = pop();
visit(p);
p = p->r;
}
} while(top);

Or something like that (not tested).

-Mike
Dec 3 '05 #2
* Aris:
Hello!
This is my problem.
I'm trying to make an inorder traversal algorithm for
a binary tree, not a recursive one, but using a stack.
Till now I got this:

void traverse(tree * p)
{
l: if(p==0) goto s;
push(p);
p=p->l; goto l;
r: visit(p);
p=p->r;
goto l;
s: if(top==0) goto x;
p=pop(); goto r;
x: ;
}

we call this function this way : traverse(root);
My question is :
how can I eliminate goto's?
Everything I've tryed is a mess.
I'll be greatfull if you help me.


I will assume that this is not HOMEWORK. But if it is then an answer
can still be helpful to others. Essentially, transform the code to
something less awful one small step at a time, preserving the code's
effect _exactly_ at each small step.

Let's start with the first label, 'l'. The 'if' there effects a jump
over the following code. So rearrange:

void traverse(tree * p)
{
l: if( p != 0 ) // if(p==0) goto s;
{
push(p);
p = p->l; goto l;
}
s: if( top == 0) goto x;
p = pop(); goto r;
r: visit(p);
p = p->r;
goto l;
x: ;
}

Now you have loop there, so express that as a loop:

void traverse(tree * p)
{
l: while( p != 0 )
{
push(p);
p = p->l;
}
s: if( top == 0) goto x;
p = pop(); goto r;
r: visit(p);
p = p->r;
goto l;
x: ;
}

The 'goto r' has no effect and so can be eliminated, along with the
labels 's' and 'r' which are then no longer referenced:

void traverse(tree * p)
{
l: while( p != 0 )
{
push(p);
p = p->l;
}
if( top == 0 ) goto x;
p = pop();
visit(p);
p = p->r;
goto l;
x: ;
}

That last goto is an outer loop, an infinite one which the goto in the
middle breaks out of:

void traverse(tree * p)
{
for( ;; )
{
while( p != 0 )
{
push(p);
p = p->l;
}
if( top == 0 ) goto x;
p = pop();
visit(p);
p = p->r;
}
x: ;
}

Finally replace the single remaining break-out-of goto with a break:

void traverse(tree * p)
{
for( ;; )
{
while( p != 0 )
{
push(p);
p = p->l;
}
if( top == 0 ) { break; }
p = pop();
visit(p);
p = p->r;
}
}

Now you can start to reason about correctness, e.g., what's that 'top'
in there? Is it perhaps a global modified by 'visit'? If so, then
that's evil and should be fixed, and if not so, then you have
non-working code.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Dec 3 '05 #3
Not only a good answer but the way to face this problems
in the future.
Gratefull!
Dec 4 '05 #4
A good introduction how to handle trees (and other data structures) can be
found in the free eBook "C++Course" . Trees are discussed here:

http://www.vias.org/cppcourse/chap21_01.html

Regards,

Hans
=============== =============== =======
Hans Lohninger
EPINA GmbH - Software Development Lohninger
www.lohninger.com
mailto:of****@e pinasoft.com
fax: +43-2233-541945
=============== =============== ========

"Aris" <na******@hotma il.com> wrote in message
news:dm******** **@usenet.otene t.gr...
Hello!
This is my problem.
I'm trying to make an inorder traversal algorithm for
a binary tree, not a recursive one, but using a stack.
Till now I got this:

void traverse(tree * p)
{
l: if(p==0) goto s;
push(p);
p=p->l; goto l;
r: visit(p);
p=p->r;
goto l;
s: if(top==0) goto x;
p=pop(); goto r;
x: ;
}

we call this function this way : traverse(root);
My question is :
how can I eliminate goto's?
Everything I've tryed is a mess.
I'll be greatfull if you help me.

Dec 4 '05 #5
Aris wrote:
Not only a good answer but the way to face this problems
in the future.
Gratefull!


Just a note: it would be useful (or maybe simply more pleasant
to whoever gave you that answer), to have quoted the message
you replied to...
Dec 5 '05 #6
Hello!
Im trying to implement a queue
using a linked list.
I've made that code
and I expected my Degueue()
function to return the value of the
key of the node I constructed.
But It does not.
In fact it returns "Empty Queue"
what am I doing wrong?
#include <stdlib.h>
#include <stdio.h>

typedef struct Queue * link;
struct Queue
{
link head;
link tail;
link next;
int key;
};

void Enqueue(link Head,link Tail,int data)
{
link ptr=(struct Queue*)malloc(s izeof(struct Queue));
ptr->key=data;
if(Head==0) Head= ptr; else Tail->next=ptr;
Tail=ptr;
}

int Dequeue(link Head,int data)
{
link temp;
if(Head!=0){
data=Head->key;
temp=Head;
Head=Head->next;
}

else
{
printf("Empty Queue\n"); return 0;
}

free(temp);
return data;
}

int main()
{
link head=0;
link tail=0;

Enqueue(head,ta il,1);

int x=Dequeue(head, x);
printf("%d\n",x );

return 0;

}

Dec 7 '05 #7

"Hans Lohninger" <ha**@lohninger .com> wrote in message
news:43******** *************** @tunews.univie. ac.at...
A good introduction how to handle trees (and other data structures) can be
found in the free eBook "C++Course" . Trees are discussed here:

http://www.vias.org/cppcourse/chap21_01.html


Except it's not really C++ is it.

Jeff

Dec 7 '05 #8
Jeff Flinn wrote:
"Hans Lohninger" <ha**@lohninger .com> wrote in message
news:43******** *************** @tunews.univie. ac.at...
A good introduction how to handle trees (and other data structures) can be
found in the free eBook "C++Course" . Trees are discussed here:

http://www.vias.org/cppcourse/chap21_01.html


Except it's not really C++ is it.

Jeff


Since when does c++ have interfaces? (see
http://www.vias.org/cppcourse/chap21_08.html) rather looks like java to
me...

- michael
Dec 7 '05 #9
Aris wrote:
Hello!
Im trying to implement a queue
using a linked list.
You know C++ already provides queues and linked list
as part of the language?

Further the code while syntactcally C++ is pretty
poor C++ design.
void Enqueue(link Head,link Tail,int data)
{
link ptr=(struct Queue*)malloc(s izeof(struct Queue)); int main()
{
link head=0;
link tail=0;

Enqueue(head,ta il,1);


head and tail are still null pointers here. You are passing
by value. All Enqueue does is malloc stuff that gets lost.
Dec 8 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
636
by: JC | last post by:
Hi, I'm looking for some help on Binary trees, in particular levels, heights etc. I need to find the levels of a tree, I also need to determine the minimum, maximum and average leaf levels. Any help would be greatly appreciated... Thank you,
2
3399
by: C-man | last post by:
Yeah, for some reason I can seem to find an algorithm that will simple but items into the tree in fashion such that a new leaf can't be added to a new level till all the leafs at the previous level are used. This would seem like an easy solution but I couldn't find one and I only could get it parsley working. Any body of a solution? Thanks
1
3407
by: Jerry Khoo | last post by:
hello, everybody, i am kinda new here, nice to meet u all. Now, i am > cs students and are now facing difficult problems in understanding > what a binary tree is, how it works, and the algorithm to display, > arrange, find, delete the leaf node in binary tree. > > I hope that anyone with expereince in building binary tree could help > me in explaining the binary tree functions, and give a sample code of > the whole picture behind the...
8
2781
by: Jerry Khoo | last post by:
hello, everybody, i am kinda new here, nice to meet u all. Now, i am cs students and are now facing difficult problems in understanding what a binary tree is, how it works, and the algorithm to display, arrange, find, delete the leaf node in binary tree. I hope that anyone with expereince in building binary tree could help me in explaining the binary tree functions, and give a sample code of the whole picture behind the tree. And...
7
3653
by: pembed2003 | last post by:
Hi, I have a question about how to walk a binary tree. Suppose that I have this binary tree: 8 / \ 5 16 / \ / \ 3 7 9 22 / \ / \ / \
4
9021
by: Tarique Jawed | last post by:
Alright I needed some help regarding a removal of a binary search tree. Yes its for a class, and yes I have tried working on it on my own, so no patronizing please. I have most of the code working, even the removal, I just don't know how to keep track of the parent, so that I can set its child to the child of the node to be removed. IE - if I had C / \ B D
0
2019
by: Bonj | last post by:
hello this is a purely algorithmical question but if i have posted to an irrelevant group, apologies. can anyone point me at some good tutorials or info about the steps involved in creating a high-end generic binary tree (or, ternary search tree). The basic method I've got at the moment is having a resource file containing a series of data structures (which represent strings), specifically organised such that a test string can be matched...
15
5100
by: Foodbank | last post by:
Hi all, I'm trying to do a binary search and collect some stats from a text file in order to compare the processing times of this program (binary searching) versus an old program using linked lists. I'm totally new to binary searches by the way. Can anyone help me with the commented sections below? Much of the code such as functions and printfs has already been completed. Any help is greatly appreciated. Thanks,
10
9783
by: free2cric | last post by:
Hi, I have a single link list which is sorted. structure of which is like typedef struct mylist { int num; struct mylist *next;
0
9511
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10412
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10200
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10142
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9021
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5422
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4093
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3703
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2909
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.