二叉樹(建樹,深度,層次遍歷……)
阿新 • • 發佈:2019-02-09
#include<stdio.h> #include<stdlib.h> #include<iostream> #define maxsize 20 using namespace std; int num=0; typedef struct Lnode { char data; struct Lnode *lchild; struct Lnode *rchild; }node,*Bitree; Bitree createbitree() { Bitree T; char ch; cin>>ch; if(ch == '#') return 0; else { T = (Bitree)malloc(sizeof(node)); T->data = ch; T->lchild = createbitree(); T->rchild = createbitree(); return T; } } void print(Bitree T) { if(T){ cout<<T->data<<" "; print(T->lchild); print(T->rchild); } } void leaves(Bitree T) { if(T) { if(T->lchild==NULL&&T->rchild==NULL){ cout<<T->data<<" "; } leaves(T->lchild); leaves(T->rchild); } } void onechild(Bitree T) { if(T) { if((T->lchild==NULL&&T->rchild!=NULL)||(T->rchild==NULL&&T->lchild!=NULL)) num++; onechild(T->lchild); onechild(T->rchild); } } int depth(Bitree T) { if(T==NULL) return 0; else{ int m = depth(T->lchild); int n = depth(T->rchild); if(m>n) return m+1; else return n+1; } } int Node (Bitree T) { if(T==NULL) return 0; else{ int m = Node(T->lchild); int n = Node(T->rchild); return m+n+1; } } void Levelorder (Bitree T) //層次遍歷 { if(T){ int front ; int rear; front = rear = 0; Bitree queue[maxsize]; queue[rear++] = T; while(front < rear) { T = queue[front++]; if(T->lchild) queue[rear++]=T->lchild; if(T->rchild ) queue[rear++]=T->rchild; cout<<T->data<<" "; } } } int main() { Bitree T; T = createbitree(); print(T); cout<<endl; cout<<"leaves of the tree:"; leaves(T); cout<<endl; onechild(T); cout<<"The tree has only one child:"<<num; cout<<endl; printf("The depth of the tree is :%d",depth(T)); cout<<endl; printf("The node of the tree is :%d",Node(T)); cout<<endl; printf("The Levelorder of the tree is:" ); Levelorder(T); }