The sword refers to Offer. The mirror image of the binary tree

Please complete a function that takes as input a binary tree and the function outputs its mirror image.

For example enter:

Mirror output:

 

Example 1:

Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]

code show as below:

class Solution {
public:
    TreeNode* mirrorTree(TreeNode* root) {
        queue<TreeNode*> q;//定义队列
        q.push(root);//将根节点入队
        while(!q.empty())
        {
            TreeNode* temp=q.front();//获取队首元素,并让队首元素出队
            q.pop();
            if(temp==NULL)
            {
                continue;
            }
            swap(temp->left,temp->right);//交换左右节点的值
            q.pop();
            if(node->left!=nullptr)//此节点的左结点都不为空时,将此结点的左节点入队
            {
                 q.push(node->left);
            }
            if(node->right!=nullptr)//此节点的右结点都不为空时,将此结点的右节点入队
            {
                 q.push(node->right);
            }//入队的结点是二叉树下一行的结点
        }
        return root;

    }
};

Guess you like

Origin blog.csdn.net/m0_62379712/article/details/131996678