非递归中序输出二叉搜索树
2010-10-10 12:16
211 查看
代码
#include <iostream> using namespace std; struct SBtee { SBtee * _p; SBtee *_l; SBtee *_r; int _data; }; void Print(SBtee * p) { cout<<p->_data<<" "; } void inorder_tree_walk(SBtee * root) { SBtee * last = (SBtee*)1; SBtee * p = root; while(p) { if(p->_r == last) { while (p!=NULL&&p->_r == last) //找到该结点的第一个父结点,其中该结点在此父结点的左子树上 { last = p; p=p->_p; } } else if (p->_l==NULL || p->_l==last) { Print(p); last = p; if (p->_r==NULL) { p=p->_p; } else { p=p->_r; } } else { p = p->_l; } } } int main(int argc, char* argv[]) { SBtee * pRoot = new SBtee; pRoot->_data = 150; pRoot->_p =NULL; SBtee * p; pRoot->_l = new SBtee; pRoot->_l->_data =60; p = pRoot->_r = new SBtee; pRoot->_r->_data =180; pRoot->_r->_p = pRoot->_l->_p = pRoot; p->_l = new SBtee; p->_l->_data =170; p->_l->_l = p->_l->_r = NULL; p->_r = new SBtee; p->_r->_data =200; p->_r->_l = p->_r->_r = NULL; p->_l->_p =p->_r->_p=p; p = pRoot->_l; p->_l = new SBtee; p->_l->_data = 30; p->_r=new SBtee; p->_r->_data =70; p->_l->_p =p->_r->_p=p; SBtee * p3 =p->_l; SBtee * p7 =p->_r; p3->_l = new SBtee; p3->_l->_data=20; p3->_l->_l=p3->_l->_r =NULL; p3->_r = new SBtee; p3->_r->_data=40; p3->_r->_l=p3->_r->_r =NULL; p3->_l->_p = p3->_r->_p = p3; p7->_l=NULL; SBtee * p13 = p7->_r = new SBtee; p7->_r->_data =130; p7->_r->_p=p7; p13->_l = new SBtee; p13->_l->_data =90; p13->_l->_l= p13->_l->_r = NULL; p13->_r = new SBtee; p13->_r->_data =131; p13->_r->_l =NULL; p13->_l->_p = p13->_r->_p = p13; p = p13->_r->_r= new SBtee; p->_data =132; p->_l = p->_r = NULL; p->_p = p13->_r; pRoot->_r= NULL; inorder_tree_walk(pRoot); return 0; }
相关文章推荐
- 算法导论第十二章-二叉搜索树的插入(递归与非递归),中序输出(递归,用栈,既不用栈也不递归)以及节点的删除
- C++ 输出全排列 简单递归 N皇后问题
- 递归反向输出字符串
- 递归程序练习:输出十进制数的二进制表示
- 递归输出出栈所有可能
- java递归无级树输出json格式
- 递归输出字符串 经典中的经典
- 递归实现文件目录的输出
- 【LeetCode】Convert Sorted Array to Binary Search Tree ---递归建立二叉搜索树
- Python 使用递归打印输出数字 (逆序和顺序)
- 多种方式实现字符串/无符号数反向输出_栈_递归_头尾指针
- 递归输出数组中最大的数
- Count and Say,统计并输出,利用递归,和斐波那契数列原理一样。
- PAT树_层序遍历叶节点、中序建树后序输出、AVL树的根、二叉树路径存在性判定、奇妙的完全二叉搜索树、最小堆路径、文件路由
- 非递归,按序输出集合的全排列
- 用递归的方法实现输出一个十进制数的每一位
- 二叉搜索树(Binary Search Tree)的递归和非递归代码实现(C++)
- 递归实现输出n个整数的全排列和所有子集
- 求一个集合的所有子集 输出一个数所有平方和的情况 背包问题的递归解决
- Java中利用递归实现斐波纳斯数列的兔子问题,动态输出兔子的总数