深入講解二叉樹——適合新手


                                                                      二叉樹 

對於一棵二叉樹,我們知道他是樹的一種特殊情況,但二叉樹在滿足某些條件的情況下可以描述大部分樹!

對於新學習樹的同學,我就先引入樹的一些概念:

一個樹是由n個元素組成的有限集合,每個元素我們叫做節點(node),特定的節點,叫根節點或者樹根(root)

一棵樹至少是有一個節點的;其他概念我們在接下來的代碼中會引入


這是不是很想一棵二叉樹呢,其實二叉樹的子節點只有1個,2個,或者沒有,其余注意的地方會在下一篇中講到

首先我們來講一個怎么儲存樹

稍微簡單點的方法  數組,稱為父親表示法

const int  m=10;

struct node{

int data,parent;

};

node tree[m];

這個不推薦使用,因為效率低下

還有很多方法這里不一一贅述

下面給出主要實現代碼

typedef struct BTNode *Position;
typedef Position BTree;
struct BTNode
{
    char data;
    Position lChild, rChild;
};

BTree CreateBTree(BTree bt, bool isRoot)
{
    char ch;
    if (isRoot)
        printf("Root: ");
    fflush(stdin);         
    scanf("%c", &ch);
    fflush(stdin);
    if (ch != '#')
    {
        isRoot = false;
        bt = new BTNode;
        bt->data = ch;  
        bt->lChild = NULL;
        bt->rChild = NULL;
        printf("%c's left child is: ", bt->data);
        bt->lChild = CreateBTree(bt->lChild, isRoot);
        printf("%c's right child is: ", bt->data);
        bt->rChild = CreateBTree(bt->rChild, isRoot);
    }
    return bt;
}

下面給出一個中序遍歷的代碼,自己沒有測試,但思路是正確的

#include<bits/stdc++.h>
using namespace std;
struct node
{
node *lchild;
node *rchild;
char data;
}bitreenode,*bitree;
void createbitree(bitree &t)
{
char c;
cin>>c;
if("#"==c)
t==NULL;
else
{
t=new bitreenode;
t->data=c;
createbitree(t->lchild);
createbitree(t->rchild);
}
}
void pre(bitree t)
{
if(t)
{
cout<<t->data<<" ";
pre(t->lchild);
pre(t->rchild);
}
}
int main()
{
bitree t;
createbitree(t);
pre(t);
return 0;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM