/*一棵具有n个结点的完全二叉树存放在二叉树的顺序存储结构中,试编写非递归算法对该树进行前序遍历。*/
#include <iostream>
#include <stack>
using namespace std;
const int MaxSize=100;
char BTree[MaxSize];
int main(){
int length;//节点个数
stack<int> s;
int i;
int root,lchild,rchild;
cout<<"输入节点个数:"<<endl;
cin>>length;
cout<<"输入顺序存储的序列"<<endl;
for(i=0;i<length;i++){
cin>>BTree[i];
}
root=0;
s.push(root);
cout<<"输出前序遍历结果为:"<<endl;
while(!s.empty()){
root=s.top();
s.pop();
cout<<BTree[root];
lchild=root*2+1;
rchild=root*2+2;
if(rchild<length) s.push(rchild);
if(lchild<length) s.push(lchild);
}
system("pause");
return 0;
}完全二叉树的顺序存储与非递归算法前序遍历
最新推荐文章于 2022-04-19 20:26:15 发布
本文介绍了如何使用栈来实现完全二叉树的前序遍历,避免了递归调用带来的内存消耗,并通过输入节点个数和顺序存储序列,演示了非递归算法的具体步骤。

617





