簡體   English   中英

C 二叉搜索樹后序遍歷迭代使用堆棧

[英]C Binary Search Tree Post Order Traversal Iteratively using Stack

我花了幾個小時試圖弄清楚為什么它不會在最后打印根節點。

它無法current = pop(&S); 在最后一次迭代中。

我不知道出了什么問題。

算法:

1.1 創建一個空棧 2.1 當 root 不是 NULL 時執行以下操作 a) 將 root 的右孩子然后 root 壓入堆棧。 b) 將 root 設置為 root 的左孩子。 2.2 從堆棧中彈出一個項目並將其設置為根。 a) 如果彈出的項目有一個右孩子並且右孩子在棧頂,則從堆棧中刪除右孩子,將根推回並將根設置為根的右孩子。 b) 否則打印 root 的數據並將 root 設置為 NULL。 2.3 當堆棧不為空時重復步驟 2.1 和 2.2。

我想象了一下,並將其畫在白板上,邏輯對我來說很好用。 但是,在實施它時,它會在最后一次迭代時崩潰。

void postOrderIterativeS1(BSTNode *root)
{
    Stack S;
    S.top = NULL;
    BSTNode *current = root;

    int shouldContinue = 1;
    while(shouldContinue)
    {

        if(current != NULL)
        {

            if(current->right != NULL){


            push(&S, current->right);
            }

            push(&S, current);



            current = current->left;
        }
        else
        {
            current = pop(&S);
            if(peek(&S) == NULL){
                shouldContinue = 0;
            }
            if(current->right != NULL && peek(&S)->item == current->right->item)
            {
                pop(&S);
                push(&S,current);
                current = current->right;
            }

            else


            {

                int items= current->item;
                printf("%d ", current->item);
                current = NULL;
            }

        }

    }
}

如果你想要完整的代碼, https://pastebin.com/z4rPebrJ

執行:

在此處輸入圖像描述

這里至少有一個問題:

  current = pop(&S);
  if (peek(&S) == NULL) {
    shouldContinue = 0; 
    // peek(&S) is NULL here 
    // but in the if below you dereference peek(&S) which is NULL
    // and therefore you get a crash
  }
  if (current->right != NULL && peek(&S)->item == current->right->item)
  {
    pop(&S);
    push(&S, current);
    current = current->right;
  }

只需更改此:

if (current->right != NULL && peek(&S)->item == current->right->item)

對此:

if (shouldContinue && current->right != NULL && peek(&S)->item == current->right->item)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM