手机版
你好,游客 登录 注册
背景:
阅读新闻

层次遍历二叉树

[日期:2014-05-27] 来源:Linux社区  作者:li_jun [字体:大 中 小]

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

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

#include <iostream>
#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<<root->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<<endl;
    }
}
int main(void)
{
    BiTree *root = CreateBiTree();
    LeveOrderTraverse(root);
    return 0;
}

二叉树的常见问题及其解决程序 http://www.linuxidc.com/Linux/2013-04/83661.htm

【递归】二叉树的先序建立及遍历 http://www.linuxidc.com/Linux/2012-12/75608.htm

在Java中实现的二叉树结构 http://www.linuxidc.com/Linux/2008-12/17690.htm

【非递归】二叉树的建立及遍历 http://www.linuxidc.com/Linux/2012-12/75607.htm

二叉树递归实现与二重指针 http://www.linuxidc.com/Linux/2013-07/87373.htm

本文永久更新链接地址:http://www.linuxidc.com/Linux/2014-05/102368.htm

linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款