数据结构--二叉树的创建、先序遍历、中序遍历、后序遍历、深度、叶子结点数
2015-11-05 10:24
513 查看
*用cin来读取char类型时,没法读入“ ”(space),所以要改用getchar()(在头文件
#include<iostream> #include<stdlib.h> #include<stdio.h> using namespace std; typedef struct BiTNode { char date; struct BiTNode *lchild, *rchild; }BiNode, *BiTree; int CreateBiTree(BiTree &T) { char date; date = getchar(); if (date == ' ') T = NULL; else { T = (BiTree)malloc(sizeof(BiNode)); T->date = date; CreateBiTree(T->lchild); CreateBiTree(T->rchild); } return 0; } void Visit(BiTree &T) { if (T->date != ' ') cout << T->date; } void PreOrder(BiTree T) { if (T) { Visit(T); PreOrder(T->lchild); PreOrder(T->rchild); } } void InOrder(BiTree T) { if (T) { InOrder(T->lchild); Visit(T); InOrder(T->rchild); } } void PostOrder(BiTree T) { if (T) { PostOrder(T->lchild); PostOrder(T->rchild); Visit(T); } } int BiTreeDepth(BiTree &T) { int leftdepth = 0; int rightdepth = 0; if (T) { cout << "left1___:" << leftdepth << endl; leftdepth = BiTreeDepth(T->lchild); cout << "left2___:" << leftdepth << endl; cout << "right1___:" << rightdepth << endl; rightdepth = BiTreeDepth(T->rchild); cout << "right2___:" << rightdepth << endl; return leftdepth > rightdepth ? (leftdepth + 1) : (rightdepth + 1); } return leftdepth > rightdepth ? leftdepth : rightdepth; } int Countleaf(BiTNode *T, int &count) { if (T) { if (!T->lchild && !T->rchild) count++; Countleaf(T->lchild, count); Countleaf(T->rchild, count); } return 1; } int main() { BiTree T; cout << "input the BiTree:" << endl; CreateBiTree(T); cout << "The PreOrder of BiTree :" << endl; PreOrder(T); cout << endl; cout << "The InOrder of BiTree :" << endl; InOrder(T); cout << endl; cout << "The PostOrder of BiTree :" << endl; PostOrder(T); cout << endl; cout << "The BiTree's depth is :" << endl; int x; x = BiTreeDepth(T); cout << x << endl; cout << "The BiTree's leafcount :" << endl; int count = 0; Countleaf(T, count); cout << count << endl; }
相关文章推荐
- AVL树-自平衡二叉查找树(Java实现)
- Lua教程(七):数据结构详解
- 解析从源码分析常见的基于Array的数据结构动态扩容机制的详解
- C#数据结构揭秘一
- 数据结构之Treap详解
- C语言二叉树的非递归遍历实例分析
- 使用C语言构建基本的二叉树数据结构
- C++非递归队列实现二叉树的广度优先遍历
- C#使用前序遍历、中序遍历和后序遍历打印二叉树的方法
- JavaScript数据结构和算法之图和图算法
- Java数据结构及算法实例:冒泡排序 Bubble Sort
- Java数据结构及算法实例:插入排序 Insertion Sort
- Java数据结构及算法实例:考拉兹猜想 Collatz Conjecture
- java数据结构之java实现栈
- java数据结构之实现双向链表的示例
- Java数据结构及算法实例:选择排序 Selection Sort
- Java数据结构及算法实例:朴素字符匹配 Brute Force
- Java数据结构及算法实例:汉诺塔问题 Hanoi
- Java数据结构及算法实例:快速计算二进制数中1的个数(Fast Bit Counting)
- java数据结构和算法学习之汉诺塔示例