数据结构_C语言_二叉树先序、中序、后序遍历
# include <stdio.h> # include <stdlib.h> typedef struct BiTreeNode { char data; struct BiTreeNode * lchild; struct BiTreeNode * rchild; }BTNode, * pBTNode; pBTNode createBTree(); void assign(pBTNode * ppn, char data, pBTNode plc, pBTNode prc); void PreTraverse(pBTNode pt); void InTraverse(pBTNode pt); void PostTraverse(pBTNode pt); int main(void) { pBTNode root = createBTree(); // printf("[root] data->%c lchild->%d rchild->%d add=%d\n", root->data, root->lchild, root->rchild, root); printf("-PreTraverse-\n"); PreTraverse(root); printf("\n"); printf("-InTraverse-\n"); InTraverse(root); printf("\n"); printf("-PostTraverse-\n"); PostTraverse(root); printf("\n"); return 0; } pBTNode createBTree() { pBTNode p1 = (pBTNode)malloc(sizeof(BTNode)); pBTNode p2 = (pBTNode)malloc(sizeof(BTNode)); pBTNode p3 = (pBTNode)malloc(sizeof(BTNode)); pBTNode p4 = (pBTNode)malloc(sizeof(BTNode)); pBTNode p5 = (pBTNode)malloc(sizeof(BTNode)); pBTNode p6 = (pBTNode)malloc(sizeof(BTNode)); assign(&p1, '1', p2, p5); assign(&p2, '2', p3, p4); assign(&p3, '3', NULL, NULL); assign(&p4, '4', NULL, NULL); assign(&p5, '5', p6, NULL); assign(&p6, '6', NULL, NULL); /* printf("[p1] data->%c lchild->%d rchild->%d add=%d\n", p1->data, p1->lchild, p1->rchild, p1); printf("[p2] data->%c lchild->%d rchild->%d add=%d\n", p2->data, p2->lchild, p2->rchild, p2); printf("[p3] data->%c lchild->%d rchild->%d add=%d\n", p3->data, p3->lchild, p3->rchild, p3); printf("[p4] data->%c lchild->%d rchild->%d add=%d\n", p4->data, p4->lchild, p4->rchild, p4); printf("[p5] data->%c lchild->%d rchild->%d add=%d\n", p5->data, p5->lchild, p5->rchild, p5); printf("[p6] data->%c lchild->%d rchild->%d add=%d\n", p6->data, p6->lchild, p6->rchild, p6); */ return p1; } void assign(pBTNode * ppn, char data, pBTNode pl, pBTNode pr) { (*ppn)->data = data; (*ppn)->lchild = pl; (*ppn)->rchild = pr; } void PreTraverse(pBTNode pt) { if (pt == NULL) return; printf("%c\n", pt->data); PreTraverse(pt->lchild); PreTraverse(pt->rchild); } void InTraverse(pBTNode pt) { if (pt == NULL) return; InTraverse(pt->lchild); printf("%c\n", pt->data); InTraverse(pt->rchild); } void PostTraverse(pBTNode pt) { if (pt == NULL) return; PostTraverse(pt->lchild); PostTraverse(pt->rchild); printf("%c\n", pt->data); }