二叉树采用顺序存储结构时的前序遍历

题目:一颗具有n个结点的二叉树采用顺序储存结构,编写算法对该二叉树进行前序遍历

C++实现如下:

#include<iostream>
using namespace std;
class SeqTree
{
public:
	SeqTree(int n) { Creat(n); }//构造二叉树,采用顺序表储存数据
	void Creat(int n);
	void PreOrder(int i, int n);
	char ch[100];//储存二叉树各个节点的数据以及表示叶节点的“#”
};

void SeqTree::Creat(int n)
{
	char t;
	t = (char)n;
	ch[0] = t;//强制转换,ch[0]处储存节点个数
	for (int i = 1; i <= n; i++)
		cin >> ch[i];
}

void SeqTree::PreOrder(int i, int n)
{
	if (ch[i] != '#') cout << ch[i] << '\t';
	else return;
	if (2 * i <= n) PreOrder(2 * i, n);//递归前序遍历左子树,其中i为根节点
	if (2 * i + 1 <= n) PreOrder(2 * i + 1, n);//递归前序遍历右子树,其中i为根节点
}
int main()
{
	int n;
	cout << "输入结点个数:";
	cin >> n;
	SeqTree T(n);
	cout << "N个结点二叉树前序遍历:" << endl;
	T.PreOrder(1, n);
	cout << endl;
	return 0;
}

 
 
 

猜你喜欢

转载自blog.csdn.net/song_10/article/details/85109545