生活随笔
收集整理的這篇文章主要介紹了
二叉树的操作1
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
【實現二叉樹的各種基本運算的算法】
問題描述:該算法的設計,要求運行結果如下所示:
二叉樹的基本運算如下:
(1)創建二叉樹
(2)輸出二叉樹:A(B(D,E(H(J,K(L,M(,N))))),C(F,G(,I)))
(3)H 結點:左孩子為# J 右孩子為 K
(4)二叉樹 bt 的高度:7
(5)釋放二叉樹 bt
數據結構實驗課的內容,寫了一天,算是寫完了。對二叉樹進行一個簡單的總結。這是二叉樹的一些基本的操作,直接上代碼
代碼如下:
#include<bits/stdc++.h>
#define telemtype char
using namespace std;typedef struct node{telemtype data;struct node *lchild,*rchild;
} *Bitree; void creatree(Bitree &tt)
{char c;cin>>c;if(c=='#') tt=NULL;else{tt=(node *)malloc(sizeof(node));tt->data=c;creatree(tt->lchild);creatree(tt->rchild);}
}void prinflr(Bitree &t)
{if(t){if(t->lchild) {printf("%c的左孩子節點為:%c\n",t->data,t->lchild->data);prinflr(t->lchild);}if(t->rchild) {printf("%c的右孩子節點為:%c\n",t->data,t->rchild->data);prinflr(t->rchild);}}
}void printtree(Bitree &t)
{if(t){printf("%c",t->data);if(!t->lchild&&!t->rchild) {return ;}else printf("(");printtree(t->lchild);if(t->rchild) cout<<",";printtree(t->rchild);printf(")");}
}
//ABD##EHJ##KL##M#N###CF##G#I##
int treehigh(Bitree &t)
{if(t==NULL) return 0;else if(!t->lchild&&!t->rchild) return 1;else return 1+max(treehigh(t->lchild),treehigh(t->rchild));
}void deletetree(Bitree &t)
{deletetree(t->lchild);deletetree(t->rchild);free(t);t=NULL;
}int main()
{Bitree t;creatree(t);cout<<"左右孩子遍歷:"<<endl;prinflr(t);cout<<"整棵樹遍歷:"<<endl;printtree(t);cout<<endl<<"樹的高度為:"<<treehigh(t)<<endl;deletetree(t);
}
努力加油a啊,(o)/~
總結
以上是生活随笔為你收集整理的二叉树的操作1的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。