树遍历没有给出预期的输出

时间:2013-10-27 14:48:29

标签: c binary-search-tree tree-traversal preorder postorder

我在下面有这个简单的代码,这是我认为遍历的标准代码。问题是我得到了一组特定输入的预期输出,而其他输出意外。例如对于输入序列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 个答案:

答案 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
  }
}