二叉树操作

#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;

typedef struct BiNide{
    char data;
    struct BiNide *lchild,*rchild;
}BiTNode,*BiTree;

void CreateBiTree(BiTree &T){//二叉树的存储 
          char ch;
          cin>>ch;
          if(ch=='#')//如果输入为#,那么当前的节点为空 
              T=NULL;
          else{
             T=new BiTNode;
             T->data=ch;
             CreateBiTree(T->lchild);
             CreateBiTree(T->rchild);
          }
} 

int Depth(BiTree T){//求二叉树的深度 
      int a,b;
      if(T==NULL)
          return 0;
      else{
         a=Depth(T->lchild);
         b=Depth(T->rchild);
         if(a>b)
            return (a+1);
         else
            return (b+1);
      }
}

int PrintAtLevel(BiTree T,int number_Of_Depth){//二叉树按层输出 
     if(T==NULL || number_Of_Depth<0)
          return 0;
     cout<<T->data<<" ";
     return PrintAtLevel(T->lchild,number_Of_Depth-1)+PrintAtLevel(T->rchild,number_Of_Depth-1);
}

int NodeCount(BiTree T){// 二叉树结点的个数 
     if(T==NULL)
         return 0;
     else
        return NodeCount(T->lchild)+NodeCount(T->rchild)+1;
}

int m=0;
int count_Of_Leaf(BiTree T){//二叉树的叶子节点的个数 
     if(T==NULL)
        return 0;
    else if(T->lchild==NULL&&T->rchild==NULL)
       m++;
    else{
       count_Of_Leaf(T->lchild);
	   count_Of_Leaf(T->rchild);
	   }
    return m;
}

void PreOrderTraverse(BiTree T){//前序遍历二叉树 
     if(T){
        cout<<T->data<<" ";
     PreOrderTraverse(T->lchild);
     PreOrderTraverse(T->rchild);
        }
}

void InOrderTraverse(BiTree T){//中序遍历二叉树 
    if(T){
        InOrderTraverse(T->lchild);
        cout<<T->data<<" ";
        InOrderTraverse(T->rchild);
    }
}

void PostOrderTraverse(BiTree T){//后序遍历二叉树 
    if(T){
        PostOrderTraverse(T->lchild);
        PostOrderTraverse(T->rchild);
        cout<<T->data<<" ";
    }
}

void ChangeLR(BiTree &T){//左右子树的交换 
      if(T==NULL)
          return ;
      else if(T->lchild==NULL&&T->rchild==NULL)
          return ;
     else{
            BiTree temp;
            temp=T->lchild;
            T->lchild=T->rchild;
            T->rchild=temp;
     }
     ChangeLR(T->lchild);
     ChangeLR(T->rchild);
     
}
int main(){
     BiTree tree;
	int number;
	cout<<"请输入建立二叉链表的序列:\n";
	CreateBiTree(tree);
	number=Depth(tree);
	cout<<"数的深度为:"<<number<<endl;
    cout<<"按层遍历后的二叉树为:"<<endl;
	PrintAtLevel(tree,number);
	cout<<endl; 
    cout<<"树的结点个数为:"<<NodeCount(tree)<<endl;
   
    cout<<"树的叶子结点个数为:"<<count_Of_Leaf(tree)<<endl;
    
	cout<<"前序遍历二叉树后为:"<<endl;
	PreOrderTraverse(tree);
	cout<<endl; 
	cout<<"中序遍历二叉树后为:"<<endl;
	InOrderTraverse(tree);
	cout<<endl; 
	cout<<"后序遍历二叉树后为:"<<endl;
	PostOrderTraverse(tree); 
	cout<<endl; 
	ChangeLR(tree);
	cout<<"左右子树交换后前序遍历的二叉树为:"<<endl;
	PreOrderTraverse(tree);
	cout<<endl; 
    return 0;

return 0;
} 
 
 
 
 

你可能感兴趣的:(二叉树操作)