🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.std.c
Article #4482

Help with tree

#4482
From: Brutii
Date: Fri, 15 Dec 1995 00:51
61 lines
1629 bytes
// I am trying to write a function that copies a binary tree without just
setting a pointer
// equal to the root pointer.  This is some of what I have.  Everything
works except the
// copyTree function.
// I figure using recursion would be easer, but if there is another way
can someone
// please show me the way.

typedef struct Node{
	int num;
	struct Node *left, *right;
} node;

typedef node *np;

np *search(np *pp, int x){
	np *qq;
	qq = pp;
	while(*qq != NULL && x != (*qq)->num)
		qq = (x < (*qq)->num ? &(*qq)->left : &(*qq)->right);
	return qq;
}                          

void *getmemory(int n){
	void *p=malloc(n);
	if (p == NULL) puts("Not enought memory\n"), exit(1);
	return p;
}

void insert(np *pp, int x){
	np *qq;
	qq = search(pp, x);
	if (*qq == NULL){
		*qq = (node *)getmemory(sizeof(node));
		(*qq)->num = x;
		(*qq)->left = (*qq)->right = NULL;
	}
}

np copyTree(np *pp){
np qq;
	if (pp != NULL){
		copyTree(&(*pp)->right);
		insert(&qq, (*pp)->num);
		copyTree(&(*pp)->left);
	}
return qq;
}

void main(void){
np root = NULL;
np newRoot;
// build tree....
//...
printTree(root, 6);  // this function prints the tree.

newRoot = copyTree(root);

printTree(newRoot, 6);
}
Technical Details
Message-ID: <4aqgq5$53f@newsbf02.news.aol.com>
Path: arc1-ca.pugleaf.net!newsbf02.news.aol.com!not-for-mail

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!newsbf02.news.aol.com!not-for-mail
From: brutii@aol.com (Brutii)
Newsgroups: comp.std.c
Subject: Help with tree
Date: 14 Dec 1995 19:51:17 -0500
Organization: America Online, Inc. (1-800-827-6364)
Sender: root@newsbf02.news.aol.com
Message-ID: <4aqgq5$53f@newsbf02.news.aol.com>
Reply-To: brutii@aol.com (Brutii)
NNTP-Posting-Host: newsbf02.mail.aol.com