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

g975291783 g975291783 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
如题,目前发现的问题好像出现在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
...全文

相关推荐

评论 3
收藏 已收藏
分享
返回顶部
g975291783
C语言 70,040 成员 243,237 内容