二叉树的建立和基本操作(递归实现)
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; }
分别输入两个二叉树来验证结果:
第一个二叉树为:
第二个二叉树为:
相关文章推荐
- 二叉树基本操作的递归实现(二叉树建立,先序,中序,后序,深度的递归遍历。广度优先,高度优先的非递归遍历)
- 二叉树的建立(非递归建立与定义建立)与基本操作(广度和深度遍历,求叶子树高)实现
- C++实现二叉树的基本操作(递归+非递归)
- 数据结构 — 二叉树的基本操作(递归实现)
- 二叉树的基本操作实现(递归和非递归)
- 八.二叉树各种操作的C语言实现 树的一些基本的操作,包括,树的建立,树的深度,
- 第4章第3节 二叉树的基本操作(非递归实现)
- 二叉树的基本操作(含遍历算法非递归实现全收录)
- 二叉树的基本操作-递归实现
- C语言实现二叉树的递归和非递归算法的基本操作
- 数据结构(C语言实现) - 二叉树的基本操作(建立,遍历,结点数,叶子结点数,高度,按树状打印,输出叶子结点等)
- c++模板实现二叉树,线索化,线索化遍历,非递归遍历及一些基本操作
- 二叉树建立与遍历递归操作c++实现
- 数据结构——排序/搜索二叉树(非递归)的基本操作实现
- 第4章第2节 二叉树的基本操作(递归实现)
- C语言实现二叉树的基本操作
- C语言实现二叉树的基本操作
- 二叉树的建立与基本操作
- 二叉树的创建、相关操作、递归和非递归式实现三种遍历
- C语言实现二叉树的基本操作