二叉树操作

#include<iostream>
using namespace std;
struct BTree
{
	char data;
	BTree *lchild;
	BTree *rchild;
};
//创建二叉树 
void CreateTree(BTree * &T)
{
	char ch;  
    cin>>ch;  
    if(ch=='#') {return;}
    else 
    {  
    	T=new BTree;
        if(!T)  cout<<"生成结点错误!"<<endl; 
        T->data=ch; 
        T->lchild=NULL;
        T->rchild=NULL;
        CreateTree(T->lchild); 
        CreateTree(T->rchild);  
    }   
}

//递归,先序遍历
void Preorder(BTree *temp)   
{
    if(temp!=NULL)
    {
        cout<<temp->data<<" ";
        Preorder(temp->lchild);
        Preorder(temp->rchild);
    }
    
}



//递归,中序遍历
void Inorder(BTree *temp)      
{
    if(temp!=NULL)
    {
        Inorder(temp->lchild);
        cout<<temp->data<<" ";
        Inorder(temp->rchild);
    }
    
}

//递归,后序遍历
void Postorder(BTree *temp)     
{
    if(temp!=NULL)
    {
        Postorder(temp->lchild);
        Postorder(temp->rchild);
        cout<<temp->data<<" ";
    }
    
}


//递归计算二叉树节点的个数
int count(BTree *temp)
{
	if(temp==NULL)
        return 0;
    else
        return count(temp->lchild)+count(temp->rchild)+1;      
}
                      



 //求二叉树叶子的个数
int findleaf(BTree *temp)
{
	int n=0; 
    if(temp==NULL)return 0;
    else
    {
        if(temp->lchild==NULL&&temp->rchild==NULL)
			return n+=1;
        else
        {
            n+=findleaf(temp->lchild);
            n+=findleaf(temp->rchild);
        }
        return n;
    }
}


//求二叉树中度数为1的结点数量
int find_1_node(BTree *temp)
{
	int m=0;
    if(temp==NULL)return 0;
    else
    {
        if(temp->lchild!=NULL&&temp->rchild!=NULL)
        {
            m+=find_1_node(temp->lchild);
            m+=find_1_node(temp->rchild);
        }
        if(temp->lchild!=NULL&&temp->rchild==NULL)
        {
            m+=1;
            m+=find_1_node(temp->lchild);
        }
        if(temp->lchild==NULL&&temp->rchild!=NULL)
        {
            m+=1;
            m+=find_1_node(temp->rchild);
        }
    }
    return m;
}

int main()
{
	BTree *root=NULL;
	cout<<"创建二叉树:"; 
	CreateTree(root);
	
	
	
    cout<<endl<<"先序遍历序列: "<<endl;
   Preorder(root);cout<<endl;
    cout<<endl<<"中序遍历序列: "<<endl;
    Inorder(root);cout<<endl;
    cout<<endl<<"后序遍历序列: "<<endl;
  
	
	
	Postorder(root);cout<<endl;cout<<endl;
	
	
	 cout<<"二叉树节点个数: "<<count(root)<<endl;
    cout<<"二叉树叶子个数:"<<findleaf(root)<<endl;
    cout<<"二叉树中度数为1的结点的数量为:"<<find_1_node(root)<<endl;
	
	
	
	return 0;
}
 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值