博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
树的先序、中序、后序和层次遍历-C++实现
阅读量:2381 次
发布时间:2019-05-10

本文共 2158 字,大约阅读时间需要 7 分钟。

一、先序遍历

1、递归算法

struct Tree{	int date;	Tree* lchild;	Tree* rchild;	Tree(int x):date(x),lchild(nullptr),rchild(nullptr){}};void PreOrder(Tree* root){	if (root != nullptr)	{		cout << root->date << " ";		PreOrder(root->lchild);		PreOrder(root->rchild);	}}

2、非递归算法

void PreOrder(Tree* root){	stack
Stack; if (root == nullptr) return; while (root != nullptr || !Stack.empty()) { while (root != nullptr) { Stack.push(root); cout << root->date << " "; root = root->lchild; } root = Stack.top(); Stack.pop(); root = root->rchild; }}

二、中序遍历

1、递归算法

void InOrder(Tree* root){	if (root != nullptr)	{		InOrder(root->lchild);		cout << root->date << " ";		InOrder(root->rchild);	}}

2、非递归算法

void InOrder(Tree* root){	stack
s; while (root != nullptr || !s.empty()) { if (root != nullptr) { s.push(root); root = root->lchild; } else { root = s.top();s.pop(); cout << root->date << " "; root = root->rchild; } }}

三、后序遍历

1、递归算法

void PostOrder(Tree* root){	if (root != nullptr)	{		PostOrder(root->lchild);		PostOrder(root->rchild);		cout << root->date << " ";	}}

2、非递归算法

void PostOrder(Tree* root){	stack
s; Tree* r = nullptr;//使用辅助指针,指向最近访问过的节点 while (root != nullptr || !s.empty()) { if (root != nullptr) { s.push(root); root = root->lchild; } else { root = s.top(); if (root->rchild != nullptr && root->rchild != r) root = root->rchild; else { s.pop(); cout << root->date << " "; r = root; root = nullptr; } } }}

四、层次遍历

1、方法1

void LevelOrder(Tree* root){	if (root == nullptr)		return;	queue
que; que.push(root); while (!que.empty()) { root = que.front(); cout << root->date << " "; que.pop(); if (root->lchild != nullptr) que.push(root->lchild); if (root->rchild != nullptr) que.push(root->rchild); }}

2、方法2

void LevelOrder(Tree* root){	if (root == nullptr)		return;	queue
que; que.push(root); while (!que.empty()) { int size = que.size(); while (size) { root = que.front(); cout << root->date << " "; que.pop(); if (root->lchild != nullptr) que.push(root->lchild); if (root->rchild != nullptr) que.push(root->rchild); --size; } }}

转载地址:http://stwab.baihongyu.com/

你可能感兴趣的文章
python 的log功能
查看>>
django 日志配置和使用
查看>>
Django分页的基本实现办法
查看>>
django 文件上传
查看>>
ptyon urlib2
查看>>
django 模板中使用配置参数
查看>>
django admin扩展-自定义后台管理界面
查看>>
django 非常实用的无限级分类功能
查看>>
百度地图api实例练习
查看>>
百度地图-非常实用的搜索自定义
查看>>
百度地图修改鼠标样式
查看>>
百度地图-修改marker图标(icon)
查看>>
百度地图-点击事件问题
查看>>
百度地图-自定义搜索、自定义marker、地图选址实用实例
查看>>
django 修改model field后台默认的显示方式
查看>>
django sql_queries 模板中显示所有的sql查询调试信息
查看>>
django mysql 连接查询join
查看>>
html 移动互联网终端的javascript touch事件,touchstart, touchend, touchmove
查看>>
大龄码农经验那么丰富,为什么很多公司都不招?
查看>>
零基础Python学习路线,小白的进阶之路!
查看>>