2016-03-27 14 views
0

Ich habe gerade angefangen zu lernen Binary Trees und ging weiter und versuchte, meine eigenen in C zu implementieren. Ich bin irgendwie verloren, warum nur InOrder Traversal korrekt angezeigt wird, während die anderen beiden falsch sind. Ich kann das wirklich nicht herausfinden. Ich habe sogar direkt versucht, Knoten einzufügen, und das Ergebnis ist das gleiche.Binäre Suche Tree Traversals

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

struct Node 
{ 
    int val; 
    struct Node *left; 
    struct Node *right; 
}; 

//Allocate Memory for New Node 
struct Node* getNewNode(int val) 
{ 
    struct Node * ptr = (struct Node*)malloc(sizeof(struct Node)); 
    ptr->val = val; 
    ptr->left = NULL; 
    ptr->right = NULL; 
    return ptr; 
} 
//Insert Node in Binary Search Tree 
struct Node* insertNode(struct Node* root,int val) 
{ 
    if(root == NULL) 
    { 
     root = getNewNode(val); 
    } 
    else if(val <= root->val) 
    { 
     root->left = insertNode(root->left,val); 
    } 
    else 
    { 
     root->right = insertNode(root->right,val); 
    } 
    return root; 

} 
void printInorder(struct Node* root) 
{ 
    if(root == NULL) return; 
    printInorder(root->left); 
    printf("%d ",root->val); 
    printInorder(root->right); 
} 
void printPostOrder(struct Node* root) 
{ 
    if(root == NULL) return; 
    printInorder(root->left); 
    printInorder(root->right); 
    printf("%d ",root->val); 
} 
void printPreOrder(struct Node*root) 
{ 
    if(root == NULL) return; 
    printf("%d ",root->val); 
    printInorder(root->left); 
    printInorder(root->right); 
} 
bool search(struct Node* root,int val) 
{ 
    if(root == NULL) 
    { 
     return false; 
    } 
    else if(val == root->val) 
    { 
     return true; 
    } 
    else if(val < root->val) 
    { 
     return search(root->left,val); 
    } 
    else 
    { 
     return search(root->right,val); 
    } 
} 
int main(void) 
{ 
    struct Node * root = NULL; //Tree is Empty 
    root = insertNode(root,15); 
    root = insertNode(root,10); 
    root = insertNode(root,8); 
    root = insertNode(root,12); 
    root = insertNode(root,20); 
    root = insertNode(root,17); 
    root = insertNode(root,25); 
    printf("Printing In-Order: \n"); 
    printInorder(root); 
    printf("\nPrinting Post-Order: \n"); 
    printPostOrder(root); 
    printf("\nPrinting Pre-Order: \n"); 
    printPreOrder(root); 

    // if(search(root,11)) 
    // { 
    // printf("\nValue Found\n"); 
    // } 
    // else 
    // { 
    // printf("\nValue Not Found\n"); 
    // } 

    return 0; 
} 

Bitte helfen Sie mir zu verstehen, wenn ich das falsch mache oder mein Verständnis von Überquerungen ist defekt. Die Ausgabe ist wie folgt: output terminal

Antwort

0

Sie haben copy-paste Fehler in printPostOrder und printPreOrder - sie beide Anruf printInorder, wo sie sollten sich anrufen.

+0

haha ​​danke :) habe letzte Nacht nicht viel geschlafen –