二叉树的构造(二叉链表)、遍历以及基本操作

来源:互联网 发布:数据库系统基础初级篇 编辑:程序博客网 时间:2024/06/11 04:11

二叉树的构造(二叉链表)、遍历以及基本操作


#include <iostream>#include <stdio.h>#include <stdlib.h>using namespace std;typedef char Elemtype;//二叉链表的链式存储//含 n 个结点的二叉链表共有 2n 个指针域,其中非空的指针域//为 n-1 ,空的指针域为 n+1 。typedef struct BiTNode{Elemtype data;BiTNode *lchild,*rchild;}BiTNode,*BiTree;void CreatBiTree(BiTree *T){Elemtype ch;scanf("%c",&ch);if(ch == ' ')*T = NULL;else{*T = (BiTNode *)malloc (sizeof(BiTNode));if(*T == NULL){cout<<"创建二叉树失败!"<<endl;exit(-1);}(*T)->data = ch;CreatBiTree(&(*T)->lchild);CreatBiTree(&(*T)->rchild);}}//先序遍历 (1)(2)(3) 先序   (2)(1)(3) 中序  (2)(3)(1) 后序void PreOrderTrverse(BiTree T){if(T){cout<<T->data; //(1)PreOrderTrverse(T->lchild);  //(2)PreOrderTrverse(T->rchild);  //(3)}//cout<<endl;}//统计二叉树中叶子节点的个数void CountLeaf(BiTree T,int &count){if(T){if(T->lchild == NULL && T->rchild == NULL)count++;CountLeaf(T->lchild,count);CountLeaf(T->rchild,count);}}//求二叉树的深度int Depth(BiTree T){int depthleft,depthright,depth;if(T == NULL)depth = 0;else{depthleft = Depth(T->lchild);depthright = Depth(T->rchild);depth = (depthleft > depthright?depthleft:depthright)+1;}return depth;}//求二叉树的深度2void Depth2(BiTree T,int level,int &depth){if(T){if(level > depth)depth = level;Depth2(T->lchild,level+1,depth);Depth2(T->rchild,level+1,depth);}}//查询二叉树的某个结点bool SearchNode(BiTree T,Elemtype elem,BiTree &T1){if(T){if(T->data == elem){T1 = T;return true;}else{if(SearchNode(T->lchild,elem,T1))return true;elsereturn SearchNode(T->rchild,elem,T1);}}else{T1 = NULL;return false;}}int main(){BiTree T;cout<<"------------创建二叉树并遍历-----------------"<<endl;cout<<"请输入要创建二叉树的数据(char):其中结点不存在的输入空格:";CreatBiTree(&T);cout<<"二叉树的先序遍历为:";PreOrderTrverse(T);cout<<endl;cout<<endl;cout<<"------------求二叉树的深度-----------------"<<endl;cout<<"二叉树的深度为(方法1):"<<Depth(T)<<endl;int depth = 0,level=1;Depth2(T,level,depth);cout<<"二叉树的深度为(方法2):"<<depth<<endl;cout<<endl;cout<<"------------求二叉树的叶子结点数-----------------"<<endl;int count = 0;CountLeaf(T,count);cout<<"二叉树中的叶子结点个数为:"<<count<<endl;cout<<endl;//循环查找, # 结束循环cout<<"------------在二叉树中查找结点-----------------"<<endl;BiTree T1;Elemtype elem;fflush(stdin);cout<<"请输入你要查找的元素(char):";scanf("%c",&elem);while(elem != '#'){if(SearchNode(T,elem,T1)== true ){cout<<"找到元素!打印结果为:";PreOrderTrverse(T1);cout<<endl;}else{cout<<"查找不到,请重新输入.";}fflush(stdin);cout<<"请输入你要查找的元素(char):";scanf("%c",&elem);}cout<<endl;return 0;}



0 0
原创粉丝点击