数据结构实验(C++)之二叉树(1)

(1) 假设二叉树采用链接存储方式存储,分别编写一个二叉树先序遍历的递归算法和非递归算法。

代码:

#include
using namespace std;
const int StackSize=100;

template
struct BiNode {
	T data;
	BiNode *lchild,*rchild;
};

template
class BiTree {
	public:
		BiTree() {
			root=Creat(root);
		}
		~BiTree() {
			Release(root);
		}
		void PreOrderWithRecursion() {
			PreOrderWithRecursion(root);
		}
		void PreOrderWithoutRecursion() {
			PreOrderWithoutRecursion(root);
		}
	private:
		BiNode *root;
		BiNode *Creat(BiNode *bt);
		void Release(BiNode *bt);
		void PreOrderWithRecursion(BiNode *bt);
		void PreOrderWithoutRecursion(BiNode *bt);
}; 

template
BiNode *BiTree::Creat(BiNode *bt) {
	static int i=0;
	char node[] = {'A','B','#','D','#','#','C','#','#'};
	T ch;
	ch=node[i];
	i++;
	if(ch=='#') {
		bt=NULL;
	}
	else {
		bt=new BiNode;
		bt->data=ch;
		bt->lchild=Creat(bt->lchild);
		bt->rchild=Creat(bt->rchild);
	}
	return bt;
}

template
void BiTree::Release(BiNode *bt) {
	if(bt!= NULL) {
		Release(bt->lchild);
		Release(bt->rchild);
		delete bt;
	}
}

template
void BiTree::PreOrderWithRecursion(BiNode *bt) {
	if(bt==NULL) return;
	else {
		cout<data<<" ";
		PreOrderWithRecursion(bt->lchild);
		PreOrderWithRecursion(bt->rchild);
	}
}

template
void BiTree::PreOrderWithoutRecursion(BiNode *bt) {
	BiNode *s[100]; 
	int top=-1;
	while(bt!=NULL || top!=-1) {
		while(bt!=NULL) {
			cout<data<<" ";
			s[++top]=bt;
			bt=bt->lchild;
		}
		if(top!=-1) {
			bt=s[top--];
			bt=bt->rchild;
		}
	}	
}

int main() {
	BiTree BT;	
	cout<<"先序递归遍历为:";
	BT.PreOrderWithRecursion();	
	cout<

数据结构实验(C++)之二叉树(1)_第1张图片

你可能感兴趣的:(C++)