遍历二叉树,利用栈和只用固定存储空间,递归和非递归。
2015-06-11 13:13
489 查看
struct BinaryTreeDate { BinaryTreeDate *parent; BinaryTreeDate *left; int key; BinaryTreeDate *right; BinaryTreeDate(int Key) :key(Key), left(nullptr), right(nullptr), parent(nullptr){} }; void Display(BinaryTreeDate *Node) { if (Node == nullptr) return; Display(Node->left); Display(Node->right); cout << Node->key << endl; } void Display1(BinaryTreeDate *Node) { stack<BinaryTreeDate *> Val, st; st.push(Node); while (!st.empty()) { BinaryTreeDate *T = st.top()->left; while (T != nullptr && T != Val.top()) { st.push(T); T = T->left; } T = st.top()->right; while (T != nullptr && T != Val.top()) { st.push(T); T = T->right; } Val.push(st.top()); st.pop(); } while (!Val.empty()) { cout << Val.top()->key << endl; Val.pop(); } } void Display2(BinaryTreeDate *Node) { stack<BinaryTreeDate *> st; BinaryTreeDate *Left = Node; BinaryTreeDate *Right = Node; st.push(Node); while (!st.empty()) { cout << st.top()->key << endl; Left = st.top()->left; Right = st.top()->right; st.pop(); if (Left != nullptr) st.push(Left); if (Right != nullptr) st.push(Right); } } void Fun(BinaryTreeDate * &Root) { while (Root->left != nullptr || Root->right != nullptr) { while (Root->left != nullptr) Root = Root->left; while (Root->right != nullptr) Root = Root->right; } } void Display3(BinaryTreeDate *Node) { BinaryTreeDate *Root = Node; cout << Node->key << endl; Fun(Root); while (Root != Node) { if (Root != Root->parent->right ) { if (Root->parent->right != nullptr) { cout << Root->key << endl; Root = Root->parent->right; Fun(Root); } else { cout << Root->key << endl; Root = Root->parent; } } else { if (Root->parent != nullptr) { cout << Root->key << endl; Root = Root->parent; } } } }
琢磨了一天搞出来的,好麻烦。。。--,--
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++编写简单的打靶游戏
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- C++中拷贝构造函数的应用详解
- C++中引用(&)的用法与应用实例分析
- C++使用CriticalSection实现线程同步实例
- C++智能指针实例详解
- 解析C++ 浮点数的格式化输出