【慢速学数据结构】树的遍历
来源:互联网 发布:直播软件收入排行榜 编辑:程序博客网 时间:2024/06/16 06:13
这虽然是个easy的话题,但我们还是要争取写出简洁和优雅的代码。
递归形式:前中后序对应的是print的位置,这里只写前序遍历。
void traverse(TreeNode *t){ if(!t) return; print(t->val); traverse(t->left); traverse(t->right);}
非递归形式:
// 前序遍历void iterativePreorder(TreeNode *t){ if(!t) return; std::stack<TreeNode*> st; st.push(t); while(!st.empty()) { TreeNode *n = st.top(); st.pop(); print(n->val); if(n->right) st.push(n->right); if(n->left) st.push(n->left); }}// 中序遍历void iterativeInorder(TreeNode *t){ if(!t) return; std::stack<TreeNode*> st; TreeNode *current = t; bool done = 0; while(!done) { // 一直往左,直到没有左儿子 if(current != nullptr) { st.push(current); current = current->left; } else { if(!st.empty()) { TreeNode *n = st.top(); st.pop(); print(n->val); current = n->right; } else done = 0; } }}// 后序遍历void iterativePostorder(TreeNode *t){ if(!t) return; std::stack<TreeNode*> s1; std::stack<TreeNode*> s2; s1.push(t); TreeNode *n; while (!s1.empty()) { n = s1.top(); s1.pop(); s2.push(n); if (n->left) s1.push(n->left); if (n->right) s1.push(n->right); } while (!s2.empty() { n = s2.top(); s2.pop(); printf(n->val); }}
0 0
- 【慢速学数据结构】树的遍历
- 【慢速学数据结构】查找树篇
- 【慢速学数据结构】散列篇
- 【慢速学数据结构】图篇
- 【慢速学数据结构】排序
- 【慢速学数据结构】集合篇
- 【慢速学数据结构】队列篇
- 【慢速学数据结构】优先队列(堆) 篇
- 【慢速学数据结构】集合(并查集)篇
- 二叉树的先序遍历------零基础学数据结构讲座
- 二叉树的中序遍历--------零基础学数据结构讲座(2)
- 数据结构 - 二叉树的遍历
- 数据结构-----二叉树的遍历
- 数据结构----二叉树的遍历
- 数据结构 二叉树的遍历
- 【数据结构】 二叉树的遍历
- 【数据结构】二叉树的遍历
- 数据结构 - 二叉树的遍历
- sublime text3 中无法输入中文的问题
- memcache 介绍及原理
- Notification的使用
- 【计算机视觉】计算机视觉领域资料收集
- [汇编]8086指令系统---算术指令(一)
- 【慢速学数据结构】树的遍历
- C++虚函数
- KMP算法详解
- vue 扩展
- Servlet数据压缩发送、默认Servlet配置
- 仿微信底部导航
- hdoj1108最小公倍数
- java实现 日期字符串 转换成 日期对象
- HDU 5728 PowMod(数论,欧拉函数的各种性质)