c++实现二叉树的先序遍历,中序遍历,后序遍历(递归方法)
来源:互联网 发布:网络带给我们的好处 编辑:程序博客网 时间:2024/05/18 01:02
这是算法导论中二叉树搜索的一个题
二叉树如图所示
c++代码
#include<iostream>#define N 7using namespace std;//定义节点class node{public: int data; node *leftChild;//指针 node *rightChild;};typedef node *BiTree;//等价node *createNode(int value)//创建节点,返回类型指针型,所以加*{ node * q = new node; q->leftChild = NULL;//leftChild指针为空 q->rightChild = NULL; q->data = value; return q;}BiTree createBiTree(){ node *p[N] = {NULL}; int array[6]={6,5,7,2,5,8};//输入的二叉树 for(int i=0;i<6;++i) p[i] = createNode(array[i]); for(int i = 0; i < N/2; i++) { p[i]->leftChild = p[i * 2 + 1]; p[i]->rightChild = p[i * 2 + 2]; } return p[0];}//访问节点中的数据int visit(BiTree tree){ return tree->data;}// 先序遍历void preorderTreeWalk(BiTree tree){ if(tree) { cout << visit(tree) << " "; preorderTreeWalk(tree->leftChild); preorderTreeWalk(tree->rightChild); }}// 中序遍历void inorderTreeWalk(BiTree tree){ if(tree) { inorderTreeWalk(tree->leftChild); cout << visit(tree) << " "; inorderTreeWalk(tree->rightChild); }}// 后序遍历void postorderTreeWalk(BiTree tree){ if(tree) { postorderTreeWalk(tree->leftChild); postorderTreeWalk(tree->rightChild); cout << visit(tree) << " "; }}int main(){ BiTree tree = createBiTree(); cout << "先序遍历结果为:"; preorderTreeWalk(tree); cout << endl; cout << "中序遍历结果为:"; inorderTreeWalk(tree); cout << endl; cout << "后序遍历结果为:"; postorderTreeWalk(tree); cout << endl; return 0;}
运行结果
阅读全文
0 0
- 二叉树T 的先序遍历、中序遍历、后序遍历(递归实现)
- c++实现二叉树的先序遍历,中序遍历,后序遍历(递归方法)
- C实现二叉树的先序遍历,中序遍历,后序遍历
- c语言实现二叉树的先序遍历,中序遍历,后序遍历
- 二叉树的先序遍历、中序遍历、后序遍历、层次遍历的递归实现
- 二叉树遍历(先序遍历、中序遍历、后序遍历)——递归方法和非递归方法
- 二叉树的遍历(2)--先序遍历,中序遍历,后序遍历(非递归)
- c语言原生实现二叉树的 非递归 中序 先序 后序 遍历
- 二叉树 非递归 先序遍历 中序遍历 后序遍历 层次遍历
- 递归法遍历二叉树 (先序遍历 中序遍历 后序遍历)
- 二叉树的遍历(1)--先序遍历,中序遍历,后序遍历
- 二叉树的遍历代码(先序遍历,中序遍历,后序遍历)
- 算法学习 - 树的三种遍历(递归实现)先序遍历,中序遍历,后序遍历
- 二叉树的中序、先序、后序遍历非递归遍历算法(使用堆栈,用循环实现)
- 二叉树遍历的非递归算法(先序、中序、后序)代码实现
- 二叉树的先序、中序、后序递归遍历和非递归遍历
- 二叉树的遍历C实现(非递归)—先序遍历
- 二叉树(一) 先序遍历、中序遍历、后续遍历、层次遍历的递归与非递归实现
- Lua、Luajit、Python、Node.js和Java性能测试对比
- Tampermonkey(油猴子)插件安装、使用
- 使用 gprof 监测程序性能 (1)
- LeetCode-19-Remove Nth Node From End of List(C语言实现)
- Python scrapy 爬取安软市场
- c++实现二叉树的先序遍历,中序遍历,后序遍历(递归方法)
- java 开发模式之七 : 适配器模式
- LEDE SAMBA
- 佛爷芸: 机器学习算法原理总结系列---算法基础之(1)机器学习介绍
- 2.尾部的零
- LeetCode #743 Network Delay Time
- 集合总结,NIO总结
- nikto使用方法笔记
- 基于jquery模板实现页面渲染