递归遍历二叉树

来源:互联网 发布:php 扩展reflection 编辑:程序博客网 时间:2024/05/02 01:12
#include <stdio.h>#include <string.h>#include <stdlib.h>// 二叉链表表示法typedef struct tag_BiTNode{struct tag_BiTNode *lchild;// 左孩子struct tag_BiTNode *rchild;// 右孩子char data;// 数据}BiTNode;// 先序遍历void xianxuOrder(BiTNode * root){// 空树 递归结束的条件if (root == NULL){return;}// 先根printf("%c  ", root->data);// 左子树xianxuOrder(root->lchild);// 右子树xianxuOrder(root->rchild);}// 中序遍历void zhongxuOrder(BiTNode* root){// 空if (root == NULL){return;}// 左子树zhongxuOrder(root->lchild);// 根节点printf("%c  ", root->data);// 右子树zhongxuOrder(root->rchild);////}// 后序遍历void houxuOrder(BiTNode* root){// 空if (root == NULL){return;}// 左子树houxuOrder(root->lchild);// 右子树houxuOrder(root->rchild);// 根节点printf("%c  ", root->data);}// 求树的叶子节点数int num = 0;void leafNum(BiTNode* root){// 空树if (root == NULL){return;}// 叶子节点if (root->lchild == NULL && root->rchild == NULL){num++;}// 遍历左子树leafNum(root->lchild);// 右子树leafNum(root->rchild);}void leafNum_plus(BiTNode* root, int *num){// 空树if (root == NULL){return;}// 叶子节点if (root->lchild == NULL && root->rchild == NULL){(*num)++;}// 遍历左子树leafNum_plus(root->lchild, num);// 右子树leafNum_plus(root->rchild, num);}int leafNum_plus2(BiTNode* root){// 空树if (root == NULL){return 0;}if (root->lchild == NULL && root->rchild == NULL){printf(" %c  ", root->data);return 1;}int left = leafNum_plus2(root->lchild);int right = leafNum_plus2(root->rchild);return left + right;}void main(){BiTNode nodeA, nodeB, nodeC, nodeD, nodeE, nodeF, nodeG;memset(&nodeA, 0, sizeof(BiTNode));memset(&nodeB, 0, sizeof(BiTNode));memset(&nodeC, 0, sizeof(BiTNode));memset(&nodeD, 0, sizeof(BiTNode));memset(&nodeE, 0, sizeof(BiTNode));memset(&nodeF, 0, sizeof(BiTNode));memset(&nodeG, 0, sizeof(BiTNode));// 赋值nodeA.data = 'A';nodeA.lchild = &nodeB;nodeA.rchild = &nodeC;nodeB.data = 'B';nodeB.lchild = &nodeD;nodeB.rchild = &nodeE;nodeC.data = 'C';nodeC.lchild = &nodeF;nodeC.rchild = &nodeG;nodeD.data = 'D';nodeE.data = 'E';nodeF.data = 'F';nodeG.data = 'G';// 先序printf("先序遍历: \n");xianxuOrder(&nodeA);printf("\n");// 中序printf("中序遍历: \n");zhongxuOrder(&nodeA);printf("\n");// hou序printf("后序遍历: \n");houxuOrder(&nodeA);printf("\n");leafNum(&nodeA);printf("叶子节点数: %d\n", num);int nuber = 0;leafNum_plus(&nodeA, &nuber);printf("叶子节点数_plus: %d\n", nuber);nuber = leafNum_plus2(&nodeA);printf("叶子节点数_plus: %d\n", nuber);system("pause");}

0 0