2016-03-27 201 views
0

我剛開始學習Binary Trees並繼續嘗試在C中實現我自己。我有點失落,爲什麼只有InOrder遍歷正確顯示,而另外兩個錯誤。我真的不知道這一點。我甚至直接嘗試插入節點,結果是一樣的。二叉搜索樹遍歷

#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; 
} 

請幫我理解,如果我這樣做是錯誤的,或者我對遍歷的理解是錯誤的。 輸出如下: output terminal

回答

0

您在printPostOrderprintPreOrder有複製粘貼錯誤 - 他們都呼籲printInorder,他們應該被自稱。

+0

哈哈謝謝:)昨晚沒睡太多 –