資料結構——二叉樹尋找兩結點的最近祖先
阿新 • • 發佈:2018-11-28
二叉樹尋找兩結點的最近祖先
#include<stdio.h> #include<stdlib.h> #include<string.h> #define OK 1 #define TRUE 1 #define FALSE 0 #define ERROR 0 typedef struct Node{ //二叉樹的鏈式儲存結點 char data; int status; int depth; struct Node *Lchild; struct Node *Rchild; }BiTNode,*BiTree; void CreateBiTree(BiTree *root){ //形參採用二級指標,實參為結點孩子域地址 char ch; ch=getchar(); if(ch=='#') *root=NULL; else{ *root=(BiTree)malloc(sizeof(BiTNode)); (*root)->data=ch; CreateBiTree(&((*root)->Lchild)); CreateBiTree(&((*root)->Rchild)); } } BiTree p,q; int count=0; void Visit(BiTree T){ if(count==0){ p=T; count++; } else { q=T; count++; } } void PreOrder(BiTree T,char e){ //先序遞迴遍歷 if(T){ if(T->data==e) Visit(T); PreOrder(T->Lchild,e); PreOrder(T->Rchild,e); } } BiTree parent(BiTree T,BiTree root){ //T為當前結點,root為根 BiTree p1; if(root==NULL) return NULL; if(root->Lchild==T||root->Rchild==T) return root; p1=parent(T,root->Lchild); if(p1!=NULL) return p1; else return (parent(T,root->Rchild)); } int h=1; //當前T結點所在層次 int depth=0; //記錄當前最大層次 void TreeDepth(BiTree T,int h){ if(T){ T->depth=h; //記錄當前結點的層次 if(h>depth) depth=h; TreeDepth(T->Lchild,h+1); TreeDepth(T->Rchild,h+1); } } int main(){ BiTree T; char m,n; CreateBiTree(&T); getchar(); m=getchar(); getchar(); n=getchar(); PreOrder(T,m); PreOrder(T,n); TreeDepth(T,h); p=parent(p,T); q=parent(q,T); while(p->data!=q->data){ if(p->depth<q->depth) q=parent(q,T); else if(p->depth>q->depth) p=parent(p,T); else if(p->depth==q->depth){ p=parent(p,T); q=parent(q,T); } } printf("%c",p->data); return 0; }