二叉树函数

时间:2010-12-17 02:48:48

标签: c binary-tree

有人可以在下面的二叉树上解释调用mystery(root)的输出吗?

struct treenode {
  int data;
  struct treenode* left;
  struct treenode* right;
}

void mystery(struct treenode* root) {
  if (root == NULL) return;
  mystery(root->right);
  printf("%d ", root->data%25);
  mystery(root->left);
}

树:

       35
    /      \
  23       17
 /  \     /
89  135  56
        /   \
       44    89
              \
              74
             /
            287     

6 个答案:

答案 0 :(得分:1)

见下文:

You call mystery(35)
the root is not null which calls mystery(17)
    mystery(17) is not null and calls mystery(17-Right)
        This is null so it Returns
    printf(17%25 == 17)
    call mystery(56)
        mystery(56) is not null and calls mystery(89)
            mystery(89) is not null and calls mystery(74)
                    mystery(74) is not null and calls mystery(74-Right)
                    mystery(74-Right) is null; return;
                printf(74%25 == 24)
                mystery(74) calls mystery(287)
                    printf(287%25 == 12)
                printf(89%25 == 14)
        printf(56%25 == 6)
        mystery(56) calls mystery(44)
                mystery(44) has no right or left child
                printf(44%25 == 19)
printf(35%25 == 10)
root calls mystery(23)
    mystery(23) calls mystery(135)
        printf(135%25 == 10)
    printf(23%25 == 23)
    mystery(23) calls mystery(89)
        printf(89%25 == 14)

答案 1 :(得分:1)

我认为这将是17 24 12 14 6 19 10 10 23 14

编辑:固定间距。

答案 2 :(得分:0)

这是不正确的。此遍历称为inorder 前17个是正确的,因为17%25 = 17接下来它应该是24,因为74%25 = 24

似乎功能还可以,所描绘的树也不对。

答案 3 :(得分:0)

17,24,12,14,6,19,10,10,23,14是正确的输出

答案 4 :(得分:0)

不,此功能无法在此树上提供此类结果。 17 24 12 14 6 19 10 10 23 14

答案 5 :(得分:0)

使用以下代码:

  

17 24 12 14 6 19 10 10 23 14

void makenode(struct treenode **n, int val) {
    *n = malloc(sizeof(struct treenode));
    (*n)->left = (*n)->right = 0;
    (*n)->data = val;
}

int main() {
    struct treenode *root;
    makenode(&root, 35);
    makenode(&root->left, 23);
    makenode(&root->right, 17);
    makenode(&root->left->left, 89);
    makenode(&root->left->right, 135);

    makenode(&root->right->left, 56);
    makenode(&root->right->left->left, 44);
    makenode(&root->right->left->right, 89);

    makenode(&root->right->left->right->right, 74);
    makenode(&root->right->left->right->right->left, 287);

    mystery(root);
    return 0;
}
相关问题