算法导论 12-1-3 中序遍历的非递归算法
来源:互联网 发布:360杀毒mac版靠谱吗 编辑:程序博客网 时间:2024/05/29 18:01
题目:设计一个中序遍历的非递归算法
思路:参照10-4-5节的思路,这一次换了一种写法,思路和之前的还是差不多。
#include <iostream>#include <cstdlib>#include <ctime>using namespace std;struct TreeNode{ int key; struct TreeNode * parent; struct TreeNode * left; struct TreeNode * right; TreeNode() { parent = NULL; left = NULL; right = NULL; }};TreeNode* createTree(TreeNode * root,int d);void printTreeM(TreeNode * root);void printTreeNo(TreeNode * root);int main (){ TreeNode*root = 0; srand(time(NULL)); int n = 13; for (int i = 0;i < n;i ++) { root = createTree(root,rand()); } // printTreeF(root); cout <<endl; printTreeM(root); cout << endl; printTreeNo(root); // printTreeNONRECURiSION(root);}TreeNode* createTree(TreeNode * root,int d){ struct TreeNode * tmp = new struct TreeNode(); tmp->key = d; if (NULL == root) { root = tmp; return root; } else { struct TreeNode* p = NULL; struct TreeNode* q = NULL; p = root; while (p != NULL) { q = p; if (d < p->key ) { p = p->left; } else { p = p->right; } } if (d < q->key) { q->left = tmp; tmp->parent =q; } else if ( d > q->key) { q->right = tmp; tmp->parent =q; } else { delete tmp; } return root; }}void printTreeM(TreeNode * root){ if (NULL == root) return; printTreeM(root->left); cout << root->key << '\t'; printTreeM(root->right);}void printTreeNo(TreeNode * p){ TreeNode * x = NULL; while (p != NULL) { if (x != p->left) { p = p->left; continue; } cout << p->key << ' '; if (p->right) { x = NULL; p = p->right; } else { do { x = p; p = p->parent; }while(p && x == p->right); } }}
0 0
- 算法导论12-1-3非递归中序遍历
- 算法导论 12-1-3 中序遍历的非递归算法
- 非递归中序遍历---算法导论12.1-3
- 非递归中序遍历---算法导论12.1-3
- 算法导论12.2-7.P165另一种非递归的中序遍历二叉树的办法
- 《算法导论》二叉树遍历的递归&非递归实现
- 算法导论第十章习题10.4-3非递归方式实现二叉树的中序遍历
- 算法导论 习题12.1-3 二叉树的无栈非递归中序遍历算法
- 二叉树的中序遍历的非递归算法
- 前序遍历 中序遍历 后续遍历的递归与非递归算法
- 中序遍历二叉树的非递归算法
- 二叉树先序、中序、后序三种遍历的非递归算法
- 中序遍历的非递归简单算法
- 二叉树先序、中序、后序三种遍历的非递归算法
- 二叉树的中序遍历(非递归算法)
- 二叉树先序、中序、后序三种遍历的非递归算法
- 二叉树前序、中序、后序三种遍历的非递归算法
- 算法导论 习题10.4-5 二叉树的遍历(非递归,O(1)存储)
- Vim简明教程【CoolShell】
- fflib并发框架学习1
- c#正则表达式用法举例
- Java多线程
- 让PHP更快的提供文件下载
- 算法导论 12-1-3 中序遍历的非递归算法
- spring mvc
- Python之美[从菜鸟到高手]--浅拷贝、深拷贝完全解读(copy源码分析)
- 项目经理应该把30%的时间用在编程上
- std::string::npos
- javascript之Ajax简介
- Codeforces(429D - Tricky Function)最近点对问题
- 将图片转换成二进制
- springMVC教程-快速入手-深入分析