Mirror image of a binary tree

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

Suppose there is a tree:

             1
            / \\
           2   3
              / \\
             4   5

Then the mirror image will

13条回答
  •  Happy的楠姐
    2020-12-01 09:13

    Well, this ques has got a lot of answers.I am posting an iterative version for this which is quite easy to understand .This uses level order Traversal.

    //Function for creating Binary Tree
    //Assuming *root for original tree and *root2 for mirror tree
    //are declared globally
    void insert(int data)
    {
    struct treenode* temp;
    if(root2 == NULL)
    {
    root2 = createNode(data);
    return;
    }
    else{
    queue q;
    q.push(root2);
    while(!q.empty())
    {
     temp = q.front();
     q.pop();
     if(temp->left)
     q.push(temp->left);
     else{
     temp->left = createNode(data);
     return;
    }
    if(temp->right)
    {
    q.push(temp->right);
    }
    else{
    temp -> right = createNode(data);
    return;
    }
    }
    }
    }
    //Iterative version for Mirror of a Binary Tree 
    void mirrorBinaryTree()
    {
    struct treenode *front;
    queue q;
    q.push(root);
    while(!q.empty())
    {
     front = q.front();
     insert(front->data);
     q.pop();
     if(front->right)
     q.push(front->right);
     if(front->left)
     q.push(front->left);
    }
    }
    

提交回复
热议问题