二叉树的克隆

#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;
}


 

你可能感兴趣的:(二叉树的克隆)