簡體   English   中英

中序遍歷迭代法

[英]Inorder Traversal Iterative Method

這是我的迭代中序遍歷代碼。 它根本沒有給我 output,它所做的只是給我一個空白屏幕。 如果有人可以查看我的代碼並告訴我我在哪里犯了錯誤,那將非常有幫助。

void iterativeInorder(struct node *root) {
    if(root==NULL) {
        return;
    }
    struct node *stack[100];
    int top=0;
    while(root) {
        if(root!=NULL) {
            stack[top++]=root;
            root=root->left;
        }
        else {
            if(top==0) {
                break;
            }
            root=stack[--top];
            printf("%d ", root->data);
            root=root->right;
        }
    }
}

錯誤在 while 條件下。 想一想:當 while 條件為真時,下一個 if 條件也為真,所以你永遠不會進入 else 塊。

你應該退出循環的唯一一次是當你點擊這個break時:

if(top==0) {
    break;
}

因此,通過將您的while轉換為以下內容來修復您的代碼:

while(true) {

暫無
暫無

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

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