二叉树全解

来源:互联网 发布:linux技术手册 第六版 编辑:程序博客网 时间:2024/06/03 06:14

二叉树的构造,前序遍历,中序遍历,后序遍历,求树高,叶子节点树分析

#include<iostream>
using namespace std;
int num=0;
struct BiNode{
 char data;
 BiNode *lchild,*rchild;
};


void Creat(BiNode* &root)
{
char ch;
//cout<<"请输入节点的值:";
cin>>ch;
if(ch=='#') root=NULL;       //建立一棵空树
else{
 root=new BiNode;
 root->data=ch;
 Creat(root->lchild);        //递归建立左子树
 Creat(root->rchild);       //递归建立右子树
 
}
}


void PreOrder(BiNode* root)
{
 if(root==NULL)return ;        //递归调用结束的条件
 else
 {
  cout<<root->data;          //访问根结点的数据域
  PreOrder(root->lchild);     //前序递归遍历root的左子树
  PreOrder(root->rchild);    //前序递归遍历root的右子树
 }
}

void InOrder(BiNode* root)
{
 if(root==NULL)return ;
 else
 {
  InOrder(root->lchild);       //中序递归遍历root的左子树
        cout<<root->data;   //访问根结点的数据域
  if(root->rchild==NULL)
   num++;                      //叶子节点数
  InOrder(root->rchild);              //中序递归遍历右子数
 }
}

void PostOrder(BiNode* root)
{
 if(root==NULL)  return ;
 else
 {
  PostOrder(root->lchild);        //后序递归遍历root的左子树
  PostOrder(root->rchild);          //后序遍历root 的右子树
  cout<<root->data;                //访问根结点的数据域
 }
}


int height(BiNode* root)
{
 if(root==NULL)return 0;
  int t1=1+height(root->lchild);
  int t2=1+height(root->rchild);
  return t1>t2?t2:t1; 
}

int main()
{
 BiNode* root;
 cout<<"请输入树的各节点:";
 Creat(root);
 cout<<"前序遍历各节点为:";
 PreOrder(root);
 cout<<"/n中序遍历各节点为:";
 InOrder(root);
 cout<<"/n后序遍历各节点为:";
 PostOrder(root);
 cout<<"/n叶子节点的个数:"<<num;
 cout<<"/n树高为: "<<height(root)<<endl;
 return 0; 
}

输入样例:ab##c##,其中##表示没有左右孩子,就是叶子节点了!

原创粉丝点击