두 갈래 나무의 복제

1616 단어
#include<iostream>
#define N 7
using namespace std;

typedef struct node
{
	struct node *leftChild;
	struct node *rightChild;
	int data;
}BiTreeNode, *BiTree;

BiTreeNode *createNode(int i)
{
	BiTreeNode * q = new BiTreeNode;
	q->leftChild = NULL;
	q->rightChild = NULL;
	q->data = i;

	return q;
}

BiTree creatBiTree()
{
	BiTreeNode *p[N] = {NULL};
	int i;
	for(i = 0; i < N; i++)
		p[i] = createNode(i + 1);

	for(i = 0; i < N/2; i++)
	{
		p[i]->leftChild = p[i * 2 + 1];
		p[i]->rightChild = p[i * 2 + 2];
	}

	return p[0];
}

int visit(BiTree T)
{
	return T->data;
}

void preOrderTraverse(BiTree T)
{
	if(T)
	{
		cout << visit(T) << " ";
		preOrderTraverse(T->leftChild);
		preOrderTraverse(T->rightChild);
	}
}

BiTree copyTree(BiTree src)
{
	if(NULL == src)
		return NULL;

	BiTree dst = new BiTreeNode;
	dst->data = src->data;
	dst->leftChild = copyTree(src->leftChild);
	dst->rightChild = copyTree(src->rightChild);

	return dst;
}

int main()
{
	BiTree src = creatBiTree();
	BiTree dst = copyTree(src);

	preOrderTraverse(src);
	cout << endl;
	preOrderTraverse(dst);
	cout << endl;
	
	return 0;
}

좋은 웹페이지 즐겨찾기