【資料結構】二叉樹的應用
阿新 • • 發佈:2018-11-19
1、分別採用遞迴和非遞迴的方式編寫兩個函式,求一棵給定二叉樹中葉子節點的個數
2、返回一棵給定二叉樹在中序遍歷下的最後一個結點
3、假設二叉樹採用鏈式方式儲存,root為其根節點,p和q分別指向二叉樹中任意兩個結點,編寫一個函式,返回p和q最近的共同祖先。
#include <stdio.h> #include <stdlib.h> typedef struct node{ char data; struct node *lchild,*rchild; }bintnode; bintnode *node,*p; int count; typedef struct stack{ bintnode *data[100]; int tag[100]; int top; }seqstack; void push(seqstack *s,bintnode *t) { s->data[s->top]=t; s->top++; } bintnode* pop(seqstack *s) { if(s->top!=0) { s->top--; return (s->data[s->top]); } else { return NULL; } } bintnode *createbintree() { char ch; bintnode *t; if((ch=getchar())=='#') { t=NULL; } else { t=(bintnode *)malloc(sizeof(bintnode)); t->data=ch; t->lchild=createbintree(); t->rchild=createbintree(); } return t; } //遞迴前序遍歷,返回葉子節點數 void digui_preorder(bintnode *t) { if(t) { if(!t->lchild && !t->rchild) { count++; return ; } digui_preorder(t->lchild); digui_preorder(t->rchild); } else return ; } //非遞迴前序遍歷,返回葉子節點數 void preorder(bintnode *t) { seqstack s; s.top=0; while((t)||(s.top!=0)) { if(t) { if(!t->lchild && !t->rchild) { count++; } push(&s,t); t=t->lchild; } else { t=pop(&s); t=t->rchild; } } } //返回非遞迴中序遍歷的最後一個結點 void inorder(bintnode *t) { seqstack s; s.top=0; while((t!=NULL) || (s.top!=0)) { if(t) { push(&s,t); t=t->lchild; } else { t=pop(&s); p=t; t=t->rchild; if(t==NULL && s.top==0) { printf("非遞迴中序遍歷情況下,最後一個結點是:%c\n",p->data); } } } } bintnode *find(bintnode *t, char str) { bintnode *p1; if(!t) return NULL; if(t->data==str) return t; else { p1=find(t->lchild,str); if(p1) return p1; else p1=find(t->rchild,str); } } bintnode *find_ancestor(bintnode *t,bintnode *p,bintnode *q) { if (!t) return NULL; if (t == p || t == q) return t; bintnode *left = find_ancestor(t->lchild, p, q); bintnode *right = find_ancestor(t->rchild, p, q); if (left && right) return t; if(left) return left; if(right) return right; } int main () { count=0; node = createbintree(); getchar(); digui_preorder(node); printf("遞迴求解:一共有%d個葉子節點\n",count); count = 0; preorder(node); printf("非遞迴求解:一共有%d個葉子節點\n",count); inorder(node); char p,q; printf("請輸入要查詢的兩個節點的值:"); scanf("%c%c",&p,&q); getchar(); bintnode *p1,*q1; p1=find(node,p); q1=find(node,q); bintnode *t1; t1=find_ancestor(node,p1,q1); printf("最近的共同祖先為:%c",t1->data); return 0; }