二叉树的深度优先搜索
来源:互联网 发布:夏米尔火花机简单编程 编辑:程序博客网 时间:2024/06/05 20:59
(一)基本思想
分析:使用两个栈来存放节点元素,栈1用来存放未遍历过的节点,栈2用来存放遍历的节点。
具体步骤:
(1)把第一个节点压进栈1。见图(a)
(2)把栈1中的栈顶节点弹出,压进栈2;若栈1为空,且被弹出节点有子节点,则把被弹出节点的子节点按从右到左的顺序压进栈1。见图(b)
(3)重复步骤2,直至栈1为空。见图(c)~图(h)
(4)至此,遍历过程结束。遍历顺序就是栈2中节点的入栈顺序。
(二)C++实现代码
#include <iostream>#include <stack>using namespace std;struct node{ int data; node *left; node *right;};void dfs(int a[], int size){ stack<node *> visited, unvisited; node nodes[size]; node *current; // 构建二叉树 for(int i = 0; i < size; i++) { nodes[i].data = a[i]; // 左子节点 int child = 2 * i + 1; if(child < size) { nodes[i].left = &nodes[child]; } else { nodes[i].left = NULL; } // 右子节点 child++; if(child < size) { nodes[i].right = &nodes[child]; } else { nodes[i].right = NULL; } } // 先把第0个节点加到unvisited栈中 unvisited.push(&nodes[0]); while (!unvisited.empty()) { current = unvisited.top(); unvisited.pop(); if(NULL != current->right) { // 把右子节点先压入unvisited栈,因为右子节点的访问次序在左子节点之后 unvisited.push(current->right); } if(NULL != current->left) { unvisited.push(current->left); } visited.push(current); cout << current->data << " "; }}int main(int argc, const char * argv[]){ int a[] = {0, 1, 2, 3, 4, 5, 6}; int size = sizeof(a)/sizeof(int); dfs(a, size); return 0;}
运行结果:
0 1 3 4 2 5 6
阅读全文
0 0
- 二叉树的深度优先搜索和广度优先搜索
- (译)二叉树的深度优先搜索
- 二叉树的深度优先搜索
- 深度优先搜索算法和广度优先搜索算法的搜索次序(二叉树)
- 二叉树的最小深度——广度优先搜索
- 二叉树的深度和广度优先搜索
- 二叉树 深度优先搜索 宽度优先搜索
- 完全二叉树深度优先搜索
- 二叉树的深度优先遍历和深度优先遍历
- 深度优先搜索二叉树递归非递归
- 广度优先搜索二叉树,并返回节点深度
- 普及练习场 深度优先搜索 加分二叉树
- 【二叉树遍历算法】——广/深度优先搜索的实现
- 二叉树 深度优先搜索(DFS)、广度优先搜索(BFS)
- 二叉树 深度优先搜索(DFS)、广度优先搜索(BFS)
- 二叉树深度优先搜索(DFS)、广度优先搜索(BFS)
- 二叉树 深度优先搜索(DFS)、广度优先搜索(BFS)
- python 生成满二叉树并进行深度优先搜索和宽度优先搜索
- 图的广度优先搜索
- Python 魔术方法(Magic Method)
- 学习Linux-4.12内核网路协议栈(3.1)——网路层的收包处理
- 关于this和super关键字为什么不能再static方法中或者静态代码块中
- 记我和ACM的初遇
- 二叉树的深度优先搜索
- 配置 struts-2.3.dtd 但一直无法提示
- 二叉树的广度优先搜索
- 【POJ】2378
- 人类社会与其发展规律
- 文档流
- OpenCV练习1:使用自定义类实现视频和帧处理的接口
- 树莓派更新源
- 代码面试指南学习记录-第一章02