二叉树的非递归后序遍历遇到的问题?只能访问叶子节点?!

g975291783 2013-10-21 04:31:51
如题,目前发现的问题好像出现在46行的判断上,问题应该是出在无法通过指针回溯节点,不知道该怎么办了,请高手现身,帮帮忙吧。


#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include "stacklink.h" //自己构造的链栈
using namespace std;
/*struct TreeNode//树的节点
{
int data;
struct TreeNode *left;
struct TreeNode *right;
};*/

//typedef struct TreeNode* BTree;

/*二叉树的递归建立
/******************/
BTree creatBTree( BTree root )
{
int data;
scanf( "%d",&data );
if( data==0 ) //结束该子树的建立
{
root=NULL;
}
else
{
root=( BTree )malloc( sizeof( struct TreeNode ) );
root->data=data;
root->left=creatBTree( root->left );
root->right=creatBTree( root->right );
}
return root;
}

void postOrder3(BTree root) //非递归后序遍历
{
STACKLINK s;
BTree cur; //当前结点
BTree pre=NULL; //前一次访问的结点
s.Push(*root);
while(!s.IsEmpty())
{
s.Pop(&cur);
cout<<cur->data<<endl;

if((cur->left==NULL&&cur->right==NULL)||
(pre!=NULL&&
(pre==cur->left||pre==cur->right) ))

{
cout<<cur->data<<" "; //如果当前结点没有孩子结点或者孩子节点都已被访问过
pre=cur;
cout<<pre->data<<endl;
}
else
{
if(cur->right!=NULL)
s.Push(*(cur->right));
if(cur->left!=NULL)
s.Push(*(cur->left));
}
}
}

int main()
{
BTree root;
cout<<"前序构造二叉树:"<<endl;
root=creatBTree( root );

cout<<"非递归后序遍历二叉树:"<<endl;
postOrder3(root); cout<<endl;
return 0;
}

//这是我的头文件
#ifndef STACKLINK_H_INCLUDED
#define STACKLINK_H_INCLUDED
#include<iostream>
using namespace std;
typedef struct TreeNode//树的节点
{
int data;
struct TreeNode *left;
struct TreeNode *right;
}TreeNode,*BTree;
//typedef struct TreeNode* BTree;

struct LNode{
TreeNode t;
LNode *next;
};
class STACKLINK{
public:
int count;
STACKLINK();
void Push(TreeNode n);
int Pop(TreeNode **p);
int IsEmpty();
void Clear();
private:
LNode *top,*p;
};
STACKLINK::STACKLINK(){
top=NULL;
count=0;
}
void STACKLINK::Push(TreeNode n){
count++;
p=new LNode ;
p->t=n;
p->next=top;
top=p;
//cout<<"入栈成功"<<n.x<<"."<<n.y<<endl;
}
int STACKLINK::Pop(TreeNode **p){
count--;
if(top==NULL){/*cout<<"栈空!"<<endl;*/ return 0;}
(*p)=&(top->t);
top=top->next;//cout<<"出栈";
return 1;
}
void STACKLINK::Clear(){

while(top!=NULL){
//cout<<top->x<<" ";
p=top;
top=top->next;
delete(p);
}
}
int STACKLINK::IsEmpty(){
if(top==NULL) return 1;
else return 0;
}
#endif // STACKLINK_H_INCLUDED
...全文
248 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
g975291783 2013-10-21
  • 打赏
  • 举报
回复
哈哈,问题解决了! 原来问题出在43行和52行左右,应该在43行的后面加上一句s.Push(*cur);并且在52行的后面加上一句s.Pop(&cur);。这样问题就解决了。按照我以前的写法会造成上一层的根节点被释放,无法留在栈中。所以只能输出最下一层的叶子节点。
熊熊大叔 2013-10-21
  • 打赏
  • 举报
回复
1. pre无用且有错 2. s.Pop(&cur); 后面进入else分支,还要重新push进去
g975291783 2013-10-21
  • 打赏
  • 举报
回复
补充一下,46行和53行都是我在调试的时候写的,没别的用途。

70,022

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧