二叉树的建立和基本操作(递归实现)

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <stdlib.h>
using namespace std;
typedef struct node
{
	int data;
	struct node* lchild;
	struct node* rchild;
}Node;
///创建二叉树(递归实现)
Node *creatbitree()
{
	Node *p;
	int n;
	cin >> n;
	if(n == 0) p = NULL;
	else
	{
		p = (Node*)malloc(sizeof(Node));
		p->data = n;
		p->lchild = creatbitree();
		p->rchild = creatbitree();
	}
	return p;
}
///先序遍历
void preorder(Node* p)
{
	if(p)
	{
		printf("%d ",p->data);
		preorder(p->lchild);
		preorder(p->rchild);
	}
}
///中序遍历
void inorder(Node* p)
{
	if(p)
	{
		inorder(p->lchild);
		printf("%d ",p->data);
		inorder(p->rchild);
	}
}
///后序遍历
void postorder(Node* p)
{
	if(p)
	{
		postorder(p->lchild);
		postorder(p->rchild);
		printf("%d ",p->data);
	}
}
///二叉树总节点数目
int Nodesum(Node* p)
{
	if(p == NULL) return 0;
	return 1+Nodesum(p->lchild)+Nodesum(p->rchild);
}
///二叉树节点的数总和为
int Sum(Node* p)
{
	if(p == NULL)  return 0;
	return p->data+Sum(p->lchild)+Sum(p->rchild);
}
///二叉树的深度为
int depthoftree(Node* p)
{
	if(!p) return 0;
	return depthoftree(p->lchild) > depthoftree(p->rchild)?depthoftree(p->lchild)+1:depthoftree(p->rchild)+1;
}
///二叉树的叶子节点为
int leafnum(Node* p)
{
	if(!p) return 0;
	else if((p->lchild == NULL)&&(p->rchild == NULL)) return 1;
	else return leafnum(p->lchild)+leafnum(p->rchild);
}

int main()
{
	Node *tree = creatbitree();
	printf("前序遍历:\n");
	preorder(tree);
	printf("\n");
    printf("中序遍历:\n");
    inorder(tree);
	printf("\n");
	printf("后序遍历:\n");
	postorder(tree);
	printf("\n");
	printf("二叉树总节点数目:");
	printf("%d\n",Nodesum(tree));
	printf("二叉树节点的数总和为:");
	printf("%d\n",Sum(tree));
	printf("二叉树的深度为:");
	printf("%d\n",depthoftree(tree));
	printf("二叉树的叶子节点为:");
	printf("%d\n",leafnum(tree));
	return 0;
}

分别输入两个二叉树来验证结果:

第一个二叉树为:

                                                                                                  
第二个二叉树为:

                                                                                                      



  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值