kachilous
kachilous

Reputation: 2529

Binary Trees Function

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
        /   \
       44    89
              \
              74
             /
            287     

Upvotes: 2

Views: 521

Answers (6)

user418748
user418748

Reputation:

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)

Upvotes: 1

Gaurav Dadhania
Gaurav Dadhania

Reputation: 5327

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

Edit: fixed spacing.

Upvotes: 1

sje397
sje397

Reputation: 41812

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

Upvotes: 0

user448516
user448516

Reputation:

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

Upvotes: 0

Om Deshmane
Om Deshmane

Reputation: 808

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

Upvotes: 0

Enrique
Enrique

Reputation: 10117

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.

Upvotes: 0

Related Questions