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/p45,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;
}
4

1 回答 1

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
  }
}
于 2013-10-27T15:02:38.490 回答