Mirror image of a binary tree

前端 未结 13 2493
时光取名叫无心
时光取名叫无心 2020-12-01 09:00

Suppose there is a tree:

             1
            / \\
           2   3
              / \\
             4   5

Then the mirror image will

13条回答
  •  醉梦人生
    2020-12-01 09:20

    Sounds like homework.

    It looks very easy. Write a recursive routine that depth-first visits every node and builds the mirror tree with left and right reversed.

    struct node *mirror(struct node *here) {
    
      if (here == NULL)
         return NULL;
      else {
    
        struct node *newNode = malloc (sizeof(struct node));
    
        newNode->value = here->value;
        newNode->left = mirror(here->right);
        newNode->right = mirror(here->left);
    
        return newNode;
      }
    }
    

    This returns a new tree - some other answers do this in place. Depends on what your assignment asked you to do :)

提交回复
热议问题