设为首页 加入收藏

TOP

层次遍历二叉树
2014-11-23 23:16:58 来源: 作者: 【 】 浏览:7
Tags:层次

按先序序列输入字符序列(其中逗号表示空节点),输出该二叉树的层次遍历序列。


层次遍历二叉树层次遍历二叉树


#include
#define END ','//表示空节点
using namespace std;
typedef char Elem_Type;
typedef struct BiTree
{
Elem_Type data;
struct BiTree *Lchild;
struct BiTree *Rchild;
}BiTree;
BiTree *CreateBiTree(void)
{
Elem_Type value;cin>>value;
if(value == END)
return NULL;
BiTree *root = new BiTree;
root->data = value;
root->Lchild = CreateBiTree();
root->Rchild = CreateBiTree();
return root;
}
int BiTreeDepth(BiTree *root)
{
if( !root )
return 0;
return max( BiTreeDepth(root->Lchild),BiTreeDepth(root->Rchild) ) + 1;
}
void PrintBiTree(BiTree *root,int level)
{
if( !root )//不写这个会有段错误发生
return;
if(level == 1 )
cout<data;
else
{
PrintBiTree(root->Lchild,level - 1);
PrintBiTree(root->Rchild,level - 1);
}
}
void LeveOrderTraverse(BiTree *root)
{
int depth = BiTreeDepth(root);
for(int i=1; i <= depth; i++)
{
PrintBiTree(root,i);
cout< }
}
int main(void)
{
BiTree *root = CreateBiTree();
LeveOrderTraverse(root);
return 0;
}


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇逆序建立链表 下一篇Linux Shell脚本的10个有用的“面..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: