層次遍歷二叉樹

先序序列輸入字符序列(其中逗號表示空節點),輸出該二叉樹的層次遍歷序列。

#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;
}
發佈了73 篇原創文章 · 獲贊 34 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章