标签:
只复习一下二叉树的遍历,其他的以后再看
表示
/* bt_data_t for bi tree */ typedef char bt_data_t; #define NULL_DATA ‘\0‘ /* data_t for queue which will hold the pointer of bitree_t */ typedef void *data_t; typedef struct tree_node_t { bt_data_t data; struct tree_node_t *lchild, *rchild; } bitree_t;
实现
bitree_t *CreateBitree(int i, bt_data_t data[], int n) { bitree_t *root; int j; root = (bitree_t *)malloc(sizeof(bitree_t)); root->data = data[i]; j = 2 * i; if ((j <= n) && (data[j] != NULL_DATA)) { root->lchild = CreateBitree(j, data, n); } else { root->lchild = NULL; } j = 2 * i + 1; if ((j <= n) && (data[j] != NULL_DATA)) { root->rchild = CreateBitree(j, data, n); } else { root->rchild = NULL; } return root; } void PreOrder(bitree_t *root) { if (NULL == root) return; //do printf("%c ", root->data); PreOrder(root->lchild); PreOrder(root->rchild); return; } void InOrder(bitree_t *root) { if (NULL == root) return; InOrder(root->lchild); //do printf("%c ", root->data); InOrder(root->rchild); return; } void PostOrder(bitree_t *root) { if (NULL == root) return; PostOrder(root->lchild); PostOrder(root->rchild); //do printf("%c ",root->data); return; } void NoOrder(bitree_t *root) { linkqueue_t *lq; /* create queue */ lq = CreateEmptyLinkqueue(); /* root node enters queue */ EnQueue(lq, root); while (!EmptyLinkqueue(lq)) { DeQueue(lq, (data_t *)(&root)); printf("%c ", root->data); if (root->lchild != NULL) { EnQueue(lq, root->lchild); } if (root->rchild != NULL) { EnQueue(lq, root->rchild); } } return; }
测试代码
int main() { bitree_t *root; bt_data_t bt_array[] = {0, /* reserved [0] */ ‘A‘, ‘B‘, ‘C‘, ‘D‘,‘E‘, 0, ‘F‘, 0, 0, ‘G‘, ‘H‘, 0, 0, ‘I‘ }; root = CreateBitree( 1, bt_array, sizeof(bt_array)/sizeof(bt_data_t) - 1); printf("PreOrder : "); PreOrder(root); printf("\n"); printf("InOrder : "); InOrder(root); printf("\n"); printf("PostOrder : "); PostOrder(root); printf("\n"); printf("NoOrder : "); NoOrder(root); printf("\n"); return 0; }
结果
PreOrder : A B D E G H C F I
InOrder : D B G E H A C I F
PostOrder : D G H E B I F C A
NoOrder : A B C D E F G H I
标签:
原文地址:http://www.cnblogs.com/vsyf/p/4921481.html