二叉樹基本實現(包含main方法)

2021-08-29 03:25:48 字數 2745 閱讀 6130

所用編譯器;devc++(有些編譯器編譯不了,建議使用devc++)

所用語言:c語言

邏輯結構:非線性結構

儲存結構:鏈式儲存結構

寫在前面:學習二叉樹之前也有找過一些學習資料,資料結構的書,部落格文章,但是都大概講述的是方法,並沒有給出完整的且比較適合初學者的,今天剛剛學習了二叉樹,趁著這股熱勁,把**敲了,個人認為這些基本操作 ,熟悉了鍊錶是如何操作,建立的,還是比較容易掌握的。下面是**,羅列了一些基本操作以及在main方法中用switch-case選單的模式來展現:

#include #include #include #include int flag = 0;

typedef struct bitnodebitnode,*bitree;

//建立乙個空的帶頭結點的二叉樹

bitree initiate()

//生成一棵以x為根節點的資料域值以lbt和rbt為左右子樹的二叉樹

bitree create(int x,bitree lbt,bitree rbt)

//將資料域資訊為x的結點插入到二叉樹bt中作為結點parent的右孩子結點。

//如果結點parent原來有左孩子結點,則將結點parent原來的左孩子結點作為結點x的左孩子結點

bitree insertl(bitree bt,int x,bitree parent)

if((p=(bitnode*)malloc(sizeof(bitnode)))==null) return null;

p->data = x;

p->lchild = null;

p->rchild = null;

if(parent->lchild==null)

parent->lchild = p;

else

return bt;

} //將資料域資訊為x的結點插入到二叉樹bt中作為結點parent的右孩子結點。

//如果結點parent原來有右孩子結點,則將結點parent原來的右孩子結點作為結點x的右孩子結點

bitree insertr(bitree bt,int x,bitree parent)

if((p=(bitnode*)malloc(sizeof(bitnode)))==null) return null;

p->data=x;

p->lchild=null;

p->rchild=null;

if(parent->rchild==null)

parent->rchild = p;

else

return bt;

}//在二叉樹中刪除左子樹,當parent或者parent的左子樹為空時刪除失敗。

//刪除成功返回根結點指標,刪除失敗返回空指標。

bitree delectl(bitree bt,bitree parent)

p = parent->lchild;

parent->lchild = null;

free(p);

printf("刪除成功!\n");

return bt;

}//在二叉樹中刪除右子樹,當parent或者parent的右子樹為空時刪除失敗。

//刪除成功返回根結點指標,刪除失敗返回空指標。

bitree delectr(bitree bt,bitree parent)

p = parent->rchild;

parent->rchild = null;

free(p);

printf("刪除成功!\n");

return bt;

}//先序遍歷

void preorder(bitree bt)

//中序遍歷

void inorder(bitree bt)

//後序遍歷

void postorder(bitree bt)

; void list()

int main()

else

break;

case 3:

printf("請輸入要插入的資料:");

scanf("%d",&x);

p=insertl(bt,x,bt->lchild);

if(p!=null)

else

printf("插入失敗!\n");

break;

case 4:

printf("請輸入要插入的資料:");

scanf("%d",&x);

p=insertr(bt,x,bt->lchild);

if(p!=null)

else

printf("插入失敗!\n");

break;

case 5:

delectl(bt,bt->lchild);

break;

case 6:

delectr(bt,bt->lchild);

break;

case 7:

preorder(bt->lchild);

break;

case 8:

inorder(bt->lchild);

break;

case 9:

postorder(bt->lchild);

break;

default:

//結束程式

break;

} printf("\n\n");

} }

二叉樹實現

include include include include define maxsize 100 define ok 1 define error 0 define true 1 define false 0 typedef int status typedef int telemtype ty...

二叉樹實現

課內最近學了二叉樹,參考書上的 做了二叉樹的實現,尚不完善,還有很多地方不明白。二叉樹實現。define maxsize 100 include using namespace std 定義二叉樹節點 class btnode void createbt btnode bt,char str voi...

二叉樹實現

pragma once include include typedef char btdatatype typedef struct binarytreenode btnode include queue.h 通過前序遍歷的陣列 abd e h cf g 構建二叉樹 btnode binarytre...