编写复制一颗二叉树的非递归算法

问题描述:设栈的类型为seqstack,initstack(s)为对栈s初始化。

基本思路:用两个栈保存左右树访问的节点,每次访问根后PUSH一下,然后pop出继续保存左右子树。

// CopyBinaryTrees.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <stdlib.h>
#include <iostream>
#include <Windows.h>

using namespace std;

typedef char element;

typedef struct bitree
{
	element data;
	struct bitree* lchild;
	struct bitree* rchild;
}bitree;

typedef struct node 
{
	bitree* data;
	struct node *next;
}node,*pnode;

class seqstack
{
private:
	node* top;//当前位置,头结点
public:
	void initstack();
	void push(bitree* bt);
	BOOL pop(bitree* &bt);
	BOOL isempty();//栈是否为空,空返回true,非空返回false
};
void seqstack::initstack()
{
	top = NULL;	
}
void seqstack::push(bitree* bt)
{
	node* p = (node*)malloc(sizeof(node));
	p->data = bt;
	p->next = top;
	top = p;
}
BOOL seqstack::pop(bitree* &bt)
{
	node* p;  
	if( isempty())  // 堆栈为空,删除失败,返回0   
		return FALSE;  
	else{  
		p = top;  
		bt = p->data;         // 将栈顶元素数据域送入item中
		p->next = NULL;
		top = top->next;   // 修改栈顶指针
		free( p );               // 释放被删除结点  
		return TRUE;                // 操作成功,返回1 
	}  
}
BOOL seqstack::isempty()
{
	if (top == NULL)
		return true;
	else
		return false;
}

void CreateBiTree(bitree* &T)
{
	char  ch;
	cin>>ch;
	if(ch=='#') T=NULL;
	else
	{
		T=(bitree *)malloc(sizeof(bitree));
		T->data=ch;
		T->lchild = NULL;
		T->rchild = NULL;
		cout<<"put in \'"<<T->data<<"\' lchild"<<endl;
		CreateBiTree(T->lchild);
		cout<<"put in \'"<<T->data<<"\' rchild"<<endl;
		CreateBiTree(T->rchild);
	}
}//CreateBiTree

bitree* copyBinaryTree(bitree *bSrc)
{
	seqstack stack_left,stack_right;
	bitree* newbt;
	if (bSrc!=NULL)
	{
		//new root
		newbt=new bitree;
		newbt->data=bSrc->data;
		newbt->lchild = NULL;
		newbt->rchild = NULL;
		//travel bt and travel newbt at the same time
		stack_left.push(bSrc);
		stack_right.push(newbt);
		while (!stack_left.isempty())
		{
			bitree* pleft;
			stack_left.pop(pleft);
			bitree* pright;
			stack_right.pop(pright);
			if (pleft->rchild!=0)
			{
				stack_left.push(pleft->rchild);
				pright->rchild=new bitree;
				pright->rchild->data=pleft->rchild->data;
				pright->rchild->lchild = NULL;
				pright->rchild->rchild = NULL;
				stack_right.push(pright->rchild);
			}
			if (pleft->lchild!=0)
			{
				stack_left.push(pleft->lchild);
				pright->lchild=new bitree;
				pright->lchild->data=pleft->lchild->data;
				pright->lchild->lchild = NULL;
				pright->lchild->rchild = NULL;
				stack_right.push(pright->lchild);
			}
		}
	}
	return newbt;
}

int _tmain(int argc, _TCHAR* argv[])
{

	printf("enter # is over,put in root node\n");
	bitree *b1 = (bitree *)malloc(sizeof(bitree));
	CreateBiTree(b1);
	bitree* b2 = copyBinaryTree(b1);
	return 0;
}
    原文作者:递归算法
    原文地址: https://blog.csdn.net/s_hehe/article/details/17002047
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞