home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: sparky!uunet!mcsun!sunic!dkuug!aud.dk!vaxc.aud.auc.dk!fischer
- From: fischer@iesd.auc.dk (Lars Peter Fischer)
- Subject: Re: What's wrong with the following code...?
- In-Reply-To: ctaylor@cs.uiuc.edu's message of 20 Dec 92 19: 11:48 GMT
- Message-ID: <FISCHER.92Dec21223932@orange.iesd.auc.dk>
- Sender: news@vaxc.aud.auc.dk (USENET News System)
- Organization: Mathematics and Computer Science, Aalborg University
- References: <BzKnzo.Gt@cs.uiuc.edu>
- Date: Mon, 21 Dec 1992 21:39:32 GMT
- Lines: 78
-
-
- [ I tried to answer by mail, but it bounced, so... ]
-
- >>>>> "Conrad" == Conrad Taylor (ctaylor@cs.uiuc.edu)
-
- Conrad> void TreeBuild(NODEPTR Root)
- Conrad> {
- Conrad> Root = NULL;
-
- Conrad> TreeInsert(6, Root);
- Conrad> TreeInsert(4, Root);
- Conrad> TreeInsert(8, Root);
- Conrad> TreeInsert(7, Root);
- Conrad> TreeInsert(9, Root);
- Conrad> TreeInsert(5, Root);
- Conrad> TreeInsert(3, Root);
- Conrad> } /* end TreeBuild */
-
-
- Note that in the above, Root is local to the function. The
- modification to Root (Root = NULL) is all fine and dandy, but in a
- calling function, using
-
- TreeBuild (r)
-
- r is *not* modified. r is passed by *value* and hence have the same
- value after the call as it had before the call.
-
- The best solution is to "return" value where possible instead of using
- side effetcs, i.e.:
-
- NODEPTR TreeBuild ()
- {
- NODEPTR Root = NULL;
-
- Root = TreeInsert (6, Root);
- ....
- Root = TreeInsert (3, Root);
-
- return Root;
- }
-
- and then use
-
- r = TreeBuild ();
-
- Likewise, TreeInsert would be modified to read something like
-
-
- NODEPTR TreeInsert(int Number, NODEPTR Root)
- {
- if (Root == NULL)
- {
- Root = (NODEPTR)malloc(sizeof(struct node));
- Root->Info = Number;
- Root->LeftTree = NULL;
- Root->RightTree = NULL;
- return Root;
- }
-
- if (Number < Root->Info)
- return TreeInsert(Number, Root->LeftTree);
-
- if (Number > Root->Info)
- return TreeInsert(Number, Root->RightTree);
-
- return Root;
- }
-
-
- Since you are returning only one value, this fits well, and in my view
- the recursive nature of the algorithm is much simpler to understand
- this way.
-
- /Lars
- --
- Lars Fischer, fischer@iesd.auc.dk | It takes an uncommon mind to think of
- CS Dept., Aalborg Univ., DENMARK. | these things. -- Calvin
-