第10週プロジェクト1-ツリー計算ライブラリ
5788 ワード
/*
*2015,
*All rights reserved
* :btree.cpp
* :
* :2015 11 1
* : , , 。
* : main , :
*(1) “A(B(D,E(H(J,K(L,M(,N))))),c(F,G(,I)))”
*(2)
*(3) ‘H’ , , ‘H’
*(4)
*(5)
*/
(1) btree.h
#ifndef BTREE_H_INCLUDED
#define BTREE_H_INCLUDED
#define MaxSize 100
typedef char ElemType;
typedef struct node
{
ElemType data; //
struct node *lchild; //
struct node *rchild; //
} BTNode;
void CreateBTNode(BTNode *&b,char *str); // str
BTNode *FindNode(BTNode *b,ElemType x); // data x
BTNode *LchildNode(BTNode *p); // *p
BTNode *RchildNode(BTNode *p); // *p
int BTNodeDepth(BTNode *b); // b
void DispBTNode(BTNode *b); //
void DestroyBTNode(BTNode *&b); //
#endif // BTREE_H_INCLUDED
(2) btree.cpp
<pre class="cpp" name="code">#include <stdio.h>
#include <malloc.h>
#include "btree.h"
void CreateBTNode(BTNode *&b,char *str) // str
{
BTNode *St[MaxSize],*p=NULL;
int top=-1,k,j=0;
char ch;
b=NULL; //
ch=str[j];
while (ch!='\0') //str
{
switch(ch)
{
case '(':
top++;
St[top]=p;
k=1;
break; //
case ')':
top--;
break;
case ',':
k=2;
break; //
default:
p=(BTNode *)malloc(sizeof(BTNode));
p->data=ch;
p->lchild=p->rchild=NULL;
if (b==NULL) //p
b=p;
else //
{
switch(k)
{
case 1:
St[top]->lchild=p;
break;
case 2:
St[top]->rchild=p;
break;
}
}
}
j++;
ch=str[j];
}
}
BTNode *FindNode(BTNode *b,ElemType x) // data x
{
BTNode *p;
if (b==NULL)
return NULL;
else if (b->data==x)
return b;
else
{
p=FindNode(b->lchild,x);
if (p!=NULL)
return p;
else
return FindNode(b->rchild,x);
}
}
BTNode *LchildNode(BTNode *p) // *p
{
return p->lchild;
}
BTNode *RchildNode(BTNode *p) // *p
{
return p->rchild;
}
int BTNodeDepth(BTNode *b) // b
{
int lchilddep,rchilddep;
if (b==NULL)
return(0); // 0
else
{
lchilddep=BTNodeDepth(b->lchild); // lchilddep
rchilddep=BTNodeDepth(b->rchild); // rchilddep
return (lchilddep>rchilddep)? (lchilddep+1):(rchilddep+1);
}
}
void DispBTNode(BTNode *b) //
{
if (b!=NULL)
{
printf("%c",b->data);
if (b->lchild!=NULL || b->rchild!=NULL)
{
printf("(");
DispBTNode(b->lchild);
if (b->rchild!=NULL) printf(",");
DispBTNode(b->rchild);
printf(")");
}
}
}
void DestroyBTNode(BTNode *&b) //
{
if (b!=NULL)
{
DestroyBTNode(b->lchild);
DestroyBTNode(b->rchild);
free(b);
}
}
(3)main関数の確立#include <stdio.h> #include "btree.h" int main() { BTNode *b,*p,*lp,*rp;; printf(" (1) :"); CreateBTNode(b,"A(B(D,E(H(J,K(L,M(,N))))),C(F,G(,I)))"); printf("
"); printf(" (2) :"); DispBTNode(b); printf("
"); printf(" (3) H :"); p=FindNode(b,'H'); if (p!=NULL) { lp=LchildNode(p); if (lp!=NULL) printf(" %c ",lp->data); else printf(" "); rp=RchildNode(p); if (rp!=NULL) printf(" %c",rp->data); else printf(" "); } else printf(" !"); printf("
"); printf(" (4) b :%d
",BTNodeDepth(b)); printf(" (5) b
"); DestroyBTNode(b); return 0; }(4)
<img src="http://img.blog.csdn.net/20151102163937093" alt="" />