0

When I use the stack to deposit the root node,only A B two root nodes can enter the stack, and then the program ends

  • input: AB@@C@D@@#
  • output: BA

Stack definition, initialization, judgment whether it is empty, into the stack, out of the stack.

//定义栈 
typedef struct
{
    char *base;//栈底指针 
    char *top;//栈顶指针
    int sta
SqStack lnitStack(SqStack & S)//返回结为构体类型的顺序栈的地址 
{
    S.base = (char*)malloc(MAXSIZE * sizeof(char)); 
    if(NULL == S.base) 
        exit(-1);
    else
    {
        S.top = S.base;
        S.stacksize = MAXSIZE;
    }
    return S;
}

void Push(SqStack & S,BiTree *p) 
{
    *(S.top)= (*p)->data;
    
    //printf("入栈:%c",*(S.top));
    S.top++;
    
}
 
void Pop(SqStack & S,BiTree* q)
{
    --S.top;
    //printf("出栈:%c",*(S.top));
    (*q)->data = *(S.top);

}
 
bool empty(SqStack S)//判断空栈
{
    if(S.base == S.top)
        return true;
    else
        return false;
}

Non-recursive mid-order traversal binary trees:

void InOrderTraverse(BiTree T)
{
    BiTree p,q;
    q = (BiTree)malloc(sizeof(BiNode));
    SqStack S;
    lnitStack(S); 
    p = T;//因为原本是指针T指向二叉树的根节点,将T赋值给p,则使指针p也指向根节点 
    while(p || !empty(S))
    {
        if(p)//如果是节点不为空(节点不为空就是把该节点当作根) 
        {
            printf("p = %c",p->data);
            Push(S,&p);//则根节点其入栈 
            p = p->lchild;//访问它的左子树 
        }
        else//当根节点为空栈为空时 
        {
            Pop(S,&q);//弹出栈顶元素--根节点 
            printf("%3c", q->data);
            p = q->rchild;//访问根节点的右子树 
        }
        
    }
    return ;
}

I want to know which step wrong, why program can't output complete results?

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
temp-guy
  • 1
  • 2

0 Answers0