C++中怎样以文本形式输出二叉树?
发布网友
发布时间:2022-05-10 21:40
我来回答
共3个回答
热心网友
时间:2023-11-03 19:56
struct BtreeNode{
int data;
int ptrLtag,ptrRtag;//左右子树存在标记:0=不存在,1=存在子树,
//这变量可取消, 改下程序就行了,
BtreeNode* left;
BtreeNode* right;
};
//前序输出
bool saveBtreePre(BtreeNode* root,ofstream& fout)
{
if(root==0)
return false;
fout<<root->data<<'\t'<<root->ptrLtag<<'\t'<<root->ptrRtag<<endl;
saveBtreePre(root->left,fout);
saveBtreePre(root->right,fout);
return true;
}
//前序从文本重构二叉树
bool bulidBtreePre(BtreeNode** root,ifstream& fin)
{
BtreeNode* node=new BtreeNode;
//char ch;
fin>>node->data;
fin>>node->ptrLtag;
fin>>node->ptrRtag;
node->left=0;
node->right=0;
*root=node;
if((*root)->ptrLtag)
{
bulidBtreePre(&(*root)->left,fin);
}
if((*root)->ptrRtag)
{
bulidBtreePre(&(*root)->right,fin);
}
return true;
}
//后序输出
bool saveBtreePost(BtreeNode* root,ofstream& fout)
{
if(root==0)
return false;
saveBtreePost(root->left,fout);
saveBtreePost(root->right,fout);
fout<<root->data<<'\t'<<root->ptrLtag<<'\t'<<root->ptrRtag<<endl;
return true;
}
//后序重建二叉树
// bStack be used to store root of subtree, which be be constructed before their parents.
bool bulidBtreePost(BtreeNode** root,ifstream& fin)
{
std::stack<BtreeNode*> bStack;
while(!fin.eof())
{
BtreeNode* node=new BtreeNode;
if(!(fin>>node->data&&fin>>node->ptrLtag&&fin>>node->ptrRtag))
break;
node->left=0;
node->right=0;
if(node->ptrLtag==0&&node->ptrRtag==0)
bStack.push(node);
else if(node->ptrLtag==1&&node->ptrRtag==1)
{
node->right=bStack.top();
bStack.pop();
node->left=bStack.top();
bStack.pop();
bStack.push(node);
}
else
{
if(node->ptrLtag==1)
{
node->left=bStack.top();
bStack.pop();
bStack.push(node);
}
else
{
node->right=bStack.top();
bStack.pop();
bStack.push(node);
}
}
}
if(bStack.size()==1)
{
*root=bStack.top();
//bStack.pop();
return true;
}
else
return false;
}
//中序类似
热心网友
时间:2023-11-03 19:56
setw() 函数
#include <iomanip>
热心网友
时间:2023-11-03 19:56
按层遍历就好