开发者

Binary Trees Function

开发者 https://www.devze.com 2023-01-30 20:04 出处:网络
Can someone explain the output of calling mystery(root) on the binary tree below? struct treenode { int data;

Can someone explain the output of calling mystery(root) on the binary tree below?

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

Tree:

       35
    /      \
  23       17
 /  \     /
89  135  56
        /开发者_如何学Go   \
       44    89
              \
              74
             /
            287     


See below trace:

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)


I think it would be 17 24 12 14 6 19 10 10 23 14

Edit: fixed spacing.


It is not correct. This traversal is called inorder The first 17 is correct since 17%25=17 next it should be 24 since 74%25=24

It seems like the function is ok maybe the depicted tree is nor right.


17,24,12,14,6,19,10,10,23,14 is correct output


No, this function can't provide such result on this tree. 17 24 12 14 6 19 10 10 23 14


Using the following code I get:

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

精彩评论

暂无评论...
验证码 换一张
取 消