簡體   English   中英

如何實現一個迭代創建二叉樹的function?

[英]How to implement a function that iteratively creates a binary tree?

我嘗試通過使用迭代 function 創建二叉樹來實現它。 我很困惑為什么我的 output 會出現無限循環。我相信正在使用的 function 沒有問題。 但是,如果有人能向我解釋到底是什么導致了這個錯誤,我將不勝感激。

#include<stdio.h>
#include<stdlib.h>

typedef struct node{
    int data;
    struct node *left,*right;
} NODE;

NODE* createNode(int ele){
    NODE* newnode = (NODE*)malloc(sizeof(NODE));
    newnode->data = ele;
    newnode->left = NULL;
    newnode->right = NULL;
    return newnode;
}

void inorder(NODE* root){
    while(root != NULL){
        inorder(root->left);
        printf(" %d ",root->data);
        inorder(root->right);
    }
}


void preorder(NODE* root){
    while(root != NULL){
        printf(" %d ",root->data);
        preorder(root->left);
        preorder(root->right);
    }
}

void postorder(NODE* root){
    while(root != NULL){
        postorder(root->left);
        postorder(root->right);
        printf(" %d ",root->data);
    }
}


void createTree(NODE** root, int ele){
    NODE* newnode = createNode(ele);
    if(*root == NULL){
        //set newnode as root
        *root = newnode;
        return;
    }
    NODE* curr = *root;
    while (1){
        // If the data of the new node is less than the data of the current node,
    // go to the left child
        if(ele <  curr->data){
            // If the left child is empty, insert the new node here
            if(curr->left == NULL){
                curr->left = newnode;
                return;
            }
            curr = curr->left;
        }
            // If the data of the new node is greater than or equal to the data of the current node,
    // go to the right child
        else{
            if (curr->right == NULL){
                curr->right = newnode;
                return; 
            }
            curr = curr->right;
        }
    }
}

int main(){
    NODE* root = NULL;
    int data;
    while(1){
    printf("Enter the data for the root node of the binary tree(Enter -1 to stop): \n");
    scanf("%d",&data);
    createTree(&root,data);
    if(data == -1){
        break;
    }
}
    printf("\nPreorder traversal:\n");
    preorder(root);

    printf("\nInorder traversal:\n");
    inorder(root);

    
    printf("\nPostorder traversal:\n");
    postorder(root);
    
    return 0;
}

在打印功能中,行

while(root != NULL){

將導致無限循環,因為root永遠不會改變。

你可能想要

if(root != NULL){

暫無
暫無

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

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