Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
569 views
in Technique[技术] by (71.8m points)

algorithm - Mirror image of a binary tree

Suppose there is a tree:

             1
            / 
           2   3
              / 
             4   5

Then the mirror image will be:

              1
             / 
            3   2
           / 
          5   4

Assume the nodes are of this structure:

struct node{
      node left;
      node right;
      int value;
}

Can someone suggest an algorithm for this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...