1、二叉树节点
代码:
//二叉树节点
#include<stdio.h>
#include <malloc.h>
#include <conio.h>
#include<iostream>
//
typedef int DataType;
typedef struct Node
{
DataType data;
struct Node *LChild;
struct Node *RChild;
}BinaryNode,*BinaryTree;
//用扩展先序遍历序列创建二叉树,如果是#当前树根置为空,否则申请一个新节点
void CreateBinaryTree(BinaryTree *bt)
{
char ch;
ch=getchar();
if(ch=='.')*bt=NULL;
else
{
*bt=(BinaryTree)malloc(sizeof(BinaryNode));
(*bt)->data=ch;
CreateBinaryTree(&((*bt)->LChild));
CreateBinaryTree(&((*bt)->RChild));
}
}
//访问根节点
void Visit(char ch)
{
printf("%c ",ch);
}
//先序遍历二叉树, root为指向二叉树(或某一子树)根结点的指针
void PreOrder(BinaryTree root)
{
if (root!=NULL)
{
Visit(root ->data); //访问根结点
PreOrder(root ->LChild); //先序遍历左子树
PreOrder(root ->RChild); //先序遍历右子树
}
}
void InOrder(BinaryTree root)
//中序遍历二叉树, root为指向二叉树(或某一子树)根结点的指针
{
if (root!=NULL)
{
InOrder(root ->LChild); //中序遍历左子树
Visit(root ->data); //访问根结点
InOrder(root ->RChild); //中序遍历右子树
}
}
//后序遍历二叉树,root为指向二叉树(或某一子树)根结点的指针
void PostOrder(BinaryTree root)
{
if(root!=NULL)
{
PostOrder(root ->LChild); //后序遍历左子树
PostOrder(root ->RChild); //后序遍历右子树
Visit(root ->data); //访问根结点
}
}
//后序遍历求二叉树的高度递归算法//
int PostTreeDepth(BinaryTree bt)
{
int hl,hr,max;
if(bt!=NULL)
{
hl=PostTreeDepth(bt->LChild); //求左子树的深度
hr=PostTreeDepth(bt->RChild); //求右子树的深度
max=hl>hr?hl:hr; //得到左、右子树深度较大者
return(max+1); //返回树的深度
}
else return(0); //如果是空树,则返回0
}
//按竖向树状打印的二叉树
void PrintTree(BinaryTree Boot,int nLayer)
{
int i;
if(Boot==NULL) return;
PrintTree(Boot->RChild,nLayer+1);
for(i=0;i<nLayer;i++)
printf(" ");
printf("%c\n",Boot->data);
PrintTree(Boot->LChi