您的位置:首页 > 其它

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

2017-08-10 19:42 706 查看
#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;
}

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

第一个二叉树为:

                                                           

 
                                     


第二个二叉树为:

                                                     

 
                                               
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: