用非递归的方式对于树的各种实现

//非递归的实现一些关于树的东西


#include<iostream>
#include<stack>


using namespace std;


typedef struct BiNode{
int data;
BiNode *lChild, *rChild;
}BiNode,BiTree;


//非递归实现前序遍历
void  preOrder(BiTree *p){
stack<BiTree*> s;
if (!p)
return;
while (p != NULL || s.empty() != 0)
{
while (p){
s.push(p);
cout << s.top()->data;
p = p->lChild;
}
p=s.top();
s.pop();
p = p->rChild;
}
}


//中序非递归实现树的遍历
void  preOrder(BiTree *p){
stack<BiTree*> s;
if (!p)
return;
while (p != NULL || s.empty() != 0)
{
while (p){
s.push(p);
p = p->lChild;
}
cout << s.top()->data;
p = s.top();
s.pop();
p = p->rChild;
}
}



//非递归实现后序遍历
/*
(1)在push的时候,先进rChild,再进lChild.因为后面要先输出左子树的   再输出右子树的
(2)判断输出该节点的的条件是:
左孩子和右孩子为空,或者孩子节点都已经访问过了
*/


/*

panduan:
cur=top;
ruguo
    s feikong
ze   
    shuchu cur.data;
pop;
pre=cur

if
youhaizi kong 
ze push youhaizi 
if 
zuohaizi kong 
ze push zuohaizi 
*/
void lastOrder(BiTree *T){
stack<BiTree *> s;
BiTree *cur;
BiTree *pre = NULL;
s.push(T);
while (s.empty() != 0){
cur = s.top();
if ((cur->lChild==NULL&&cur->rChild==NULL)||
(pre!=NULL&&(pre==cur->lChild||pre==cur->rChild)))
{
cout << cur->data;
s.pop();
pre = cur;
}
if (cur->rChild != NULL)
s.push(cur->rChild);
if (cur->lChild != NULL)
s.push(cur->lChild);
}
}


/* 非递归实现左右子树的交换,如果要看一下是否成功交换了,
则可以在调换之后和之前进行一下前序遍历
*/
int Change(BiTree *T){
stack<BiTree *> s;
BiTree *p;
if (T == NULL)
return 0;
s.push(T);
while (s.empty() != 0){
T = s.top();
s.pop();
p = T->lChild;
T->lChild = T->rChild;
T->rChild = p;
if (T->rChild)
s.push(T->rChild);
if (T->lChild)
s.push(T->rChild);
}
return 1;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值