二叉树后序遍历
来源:互联网 发布:易语言编程如何写 编辑:程序博客网 时间:2024/05/17 07:10
分别用了三种不同的方法实现了二叉树的后序遍历。
/*input:210 5 4 -1 -1 -1 20 19 -1 -1 40 -1 -130 10 8 20 -1 -1 -1 -1 50 40 -1 45 -1 -1 -1output:4 5 19 40 20 1020 8 10 45 40 50 30*/#include<iostream>#include<stack>using namespace std;struct BTreeNode{ //二叉树 int data; BTreeNode *lchild; BTreeNode *rchild; BTreeNode *parent;};struct snode{ //设置访问标识 BTreeNode *node; bool flag;};/*void PostOrder(BTreeNode *t){ //递归方法 if(t == NULL)return ; PostOrder(t->lchild); PostOrder(t->rchild); cout<<t->data<<' ';}*//*void PostOrder(BTreeNode *t){ //设置访问标识,第一次为访问完左子树,第二次为访问完右子树。二次访问即刻输出结点。 stack<snode> s; snode temp; while(!s.empty() || t != NULL){ while(t != NULL){ temp.node = t; temp.flag = false; s.push(temp); t = t->lchild; } if(!s.empty()){ temp = s.top(); s.pop(); t = temp.node; if(temp.flag){ cout<<t->data<<' '; t = NULL; } else{ temp.flag = true; s.push(temp); t = t->rchild; } } }}*/void PostOrder(BTreeNode *t){ //采取根右左的存放方式,用栈实现后序遍历。设置访问标识,注意第一次放入栈,放入的是根,第二次调整其顺序。 stack<snode> s; snode temp,ltemp,rtemp; temp.node = t; temp.flag = false; s.push(temp); while(!s.empty()){ temp = s.top(); s.pop(); if(temp.flag)cout<<temp.node->data<<' '; else{ temp.flag = true; s.push(temp); if(temp.node->rchild != NULL){ rtemp.flag = false; rtemp.node = temp.node->rchild;s.push(rtemp); } if(temp.node->lchild != NULL){ ltemp.flag = false; ltemp.node = temp.node->lchild;s.push(ltemp); } } }}void Create(BTreeNode *&t){ //(测试用)以先序遍历构建二叉树int x;cin>>x;if(x == -1)t = NULL;else{t = new BTreeNode;t->data = x;Create(t->lchild);Create(t->rchild);}}int main(){BTreeNode *root = NULL;int t;cin>>t;while(t--){Create(root);PostOrder(root);cout<<endl;}return 0;}
- 二叉树后序遍历
- 二叉树后序遍历
- 二叉树后序遍历(递归)
- 二叉树后序遍历
- 数据结构 -- 二叉树后序遍历
- 二叉树后序遍历
- 二叉树后序遍历
- 二叉树后序遍历
- 二叉树后序遍历
- 二叉树后序遍历
- 二叉树后序遍历算法
- 二叉树后序遍历实例
- 二叉树后序遍历
- 二叉树后序遍历
- binTreePosterorderTraversal二叉树后序遍历
- hdu1710二叉树后序遍历
- 二叉树后序遍历
- [模板]二叉树后序遍历
- LNK2005 LNK1169 Error and LNK4098 Warning LINK : warning LNK4075:
- 铁子同学,我的理想
- 把爱融入程序——程序,源自生活,高于生活
- 二叉树中序遍历
- 关于fedora中ipv6使用的一些心得
- 二叉树后序遍历
- hdu 4411 Arrest(最小费用最大流)
- AVL树的LR和RL旋转
- 支持向量机通俗导论(理解SVM的三层境界)
- HDU 1033 Edge
- IOS多线程编程之Grand Central Dispatch(GCD)介绍和使用
- 教你如何迅速秒杀掉:99%的海量数据处理面试题
- LeetCode: Binary Tree Level Order Traversal II
- java基础学习__多线程(停止线程,守护线程,join方法)