本文主要是介绍算法上对二叉树进行(前序,中序,后序)遍历,对树高,叶子个数,节点个数挑战大礼包!!!,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
#include "stdio.h"
#include "malloc.h"
typedef int TelernType;typedef struct BTreeNode
{TelernType data; //树的数据域为字符型struct BTreeNode* LChild; //*左孩子指针struct BTreeNode* RChild; //*右孩子指针int height;
}BTree;BTree* CreatBTree()
{BTree* T;char x;scanf_s("%c", &x); getchar();if (x == '#') T = NULL;else{T = new BTree;T->data = x;printf(" 请输入 %c 结点的左孩子:", T->data);T->LChild = CreatBTree();printf(" 请输入 %c 结点的右孩子:", T->data);T->RChild = CreatBTree();}return T;
}
//前序递归遍历二叉树
void PreOrder(BTree* T)
{if (T == NULL)return;printf("%c",T->data);PreOrder(T->LChild);PreOrder(T->RChild);
}void InOrder(BTree* T)
{if (T == NULL)return;InOrder(T->LChild);printf("%c",T->data);InOrder(T->RChild);
}void PostOrder(BTree* T)
{if (T == NULL)return;PostOrder(T->LChild);PostOrder(T->RChild);printf("%c",T->data);
}int TreeHeight(BTree* T)
{int LHeight, RHeight;if (T == NULL)return 0;LHeight = TreeHeight(T->LChild);RHeight = TreeHeight(T->RChild);T->height = (LHeight>RHeight)?LHeight+1:RHeight+1;return T->height;
}
int Countnum(BTree* T)
{if (T == NULL) {return 0;}else if ((T->LChild == NULL) && (T->RChild == NULL)) {return 1;}else {return Countnum(T->LChild) + Countnum(T->RChild);}
}void main()
{BTree * T=NULL;int k;do{printf("\n\n\n\n");printf("\t\t\t 树 子系统\n");printf("\t\t******************************\n");printf("\t\t* 1----建二叉树 *\n");printf("\t\t* 2----前序遍历 *\n");printf("\t\t* 3----中序遍历 *\n");printf("\t\t* 4----后序遍历 *\n");printf("\t\t* 5----求树高度 *\n");printf("\t\t* 6----叶子个数 *\n");printf("\t\t* 7----节点个数 *\n");printf("\t\t* 0----返 回 *\n");printf("\t\t******************************\n");printf("\t\t 请选择菜单项(0-7):");scanf_s("%d", &k); getchar();if (k == 1){printf("\n 请输入此树的根结点:");T=CreatBTree();}else if (k == 2){printf("\n 此树前序遍历的顺序:");PreOrder(T);}else if (k == 3){printf("\n 此树中序遍历的顺序:");InOrder(T);}else if (k == 4) //查找线性表中元素值为x的位置{printf("\n 此树后序遍历的顺序:");PostOrder(T);}else if (k == 5) //输出链表{printf("\n此树的高度是:%d", TreeHeight(T));}else if (k == 6) //输出链表{printf("\n此树叶子个数是:%d", Countnum(T));}if (k == 0){break;}} while (k != 0);
}
这篇关于算法上对二叉树进行(前序,中序,后序)遍历,对树高,叶子个数,节点个数挑战大礼包!!!的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!