2013-10-27 22 views
0

我有下面这个简单的代码,这是我相信遍历的标准。问题是我得到的是一组特定的输入的预期输出,而其他输入是出乎意料的。例如对于输入序列15,3,6,11,45,54,65,3,66我收到预期的预订o/p:15,3,6,11,45,54,65,66。但对于序列45,3,54,65,23,66,5,3我预计预购o/p 45,3,23,5,54,65,66,但我得到45 3 5 23 54 65 66。 对于后序,我得到意外的两个序列,得到3,6,11,45,54,65,66,153,5,23,54,65,66,45,而我预计11,6,3,66,65,54,45,155,23,3,66,65,54,45分别。我是否理解错误或者存在与我的代码有关的问题?树遍历不给予预期的输出

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

typedef struct treenode 
{ 
    int val; 
    struct treenode *left; 
    struct treenode *right; 
} bnode; 

bnode *rootnd = NULL; 

bnode * ins_node(bnode *bootstrap, bnode *newnode) 
{ 
    if (bootstrap == NULL) 
    { 
    bootstrap = newnode; 
    } 
    else if (newnode->val < bootstrap->val) 
    bootstrap->left = ins_node(bootstrap->left, newnode); 
    else if (newnode->val > bootstrap->val) 
    bootstrap->right = ins_node(bootstrap->right, newnode); 

    return bootstrap; 
} 

void print_tree_inorder(bnode *root) 
{ 
    if (root != NULL) 
    { 
    print_tree_inorder(root->left); 
    printf("%d ", root->val); 
    print_tree_inorder(root->right); 
    } 
} 

void print_tree_postorder(bnode *root) 
{ 
    if (root != NULL) 
    { 
    print_tree_inorder(root->left); 
    print_tree_inorder(root->right); 
    printf("%d ", root->val); 
    } 
} 

void print_tree_preorder(bnode *root) 
{ 
    if (root != NULL) 
    { 
    printf("%d ", root->val); 
    print_tree_inorder(root->left); 
    print_tree_inorder(root->right); 
    } 
} 

int main(int argc, char *argv[]) 
{ 
    int insval; 

    printf("Keep entering numbers... press 0 to finish\n"); 

    while (1) 
    { 
    scanf("%d", &insval); 

    if (insval == 0) 
     break; 

    bnode *nd = malloc(sizeof(bnode)); 
    nd->val = insval; 
    nd->left = NULL; 
    nd->right = NULL; 

    if (rootnd == NULL) 
    { 
     rootnd = nd; 
    } 
    else 
     ins_node(rootnd, nd); 
    } 

    if (atoi(argv[1]) == 1) 
    print_tree_preorder(rootnd); 
    else if (atoi(argv[1]) == 2) 
    print_tree_inorder(rootnd); 
    else 
    print_tree_postorder(rootnd); 

    return 0; 
} 

回答

1

你的程序不递归调用自己,他们应该。请参阅下面的代码中的评论。

void print_tree_inorder(bnode *root) 
{ 
    if (root != NULL) 
    { 
    print_tree_inorder(root->left); 
    printf("%d ", root->val); 
    print_tree_inorder(root->right); 
    } 
} 

void print_tree_postorder(bnode *root) 
{ 
    if (root != NULL) 
    { 
    print_tree_inorder(root->left); // should be print_tree_postorder 
    print_tree_inorder(root->right); // same 
    printf("%d ", root->val); 
    } 
} 

void print_tree_preorder(bnode *root) 
{ 
    if (root != NULL) 
    { 
    printf("%d ", root->val); 
    print_tree_inorder(root->left); // should be print_tree_preorder 
    print_tree_inorder(root->right); // ditto 
    } 
} 
+0

omg .. !!在复制粘贴以制作另一个例程时忘记更改名称是一个错误。 –