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

博客围绕二叉树展开,假设其采用链接存储方式,给出了编写二叉树先序遍历的递归算法和非递归算法的要求,并附上了相关代码,聚焦于信息技术领域的数据结构与算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

代码:

#include<iostream>
using namespace std;
const int StackSize=100;

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

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

template<class T>
BiNode<T> *BiTree<T>::Creat(BiNode<T> *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<T>;
		bt->data=ch;
		bt->lchild=Creat(bt->lchild);
		bt->rchild=Creat(bt->rchild);
	}
	return bt;
}

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

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

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

int main() {
	BiTree<char> BT;	
	cout<<"先序递归遍历为:";
	BT.PreOrderWithRecursion();	
	cout<<endl;
	cout<<"先序非递归遍历为:";
	BT.PreOrderWithoutRecursion();	
	return 0;
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值