【Jianzhi 27】The mirror image of the binary tree

Method 1: Recursive post-order traversal of the binary tree: time O(n), space O(n)

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    
    
public:
    TreeNode* mirrorTree(TreeNode* root) 
    {
    
    
        // 1.后序遍历二叉树,交换二叉树的左右指针域的指向
        if (root == nullptr)
            return root;
        mirrorTree(root->left);
        mirrorTree(root->right);
        swap(root->left, root->right);
        return root;
    }
};

Method 2: Use the stack to traverse first: time O(n), space O(n)

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    
    
public:
    TreeNode* mirrorTree(TreeNode* root) 
    {
    
    
        // 2.借助栈:先序遍历
        if (root == nullptr)
            return root;
        stack<TreeNode*> stc;
        stc.push(root);
        while (!stc.empty())
        {
    
    
            TreeNode* node = stc.top();
            stc.pop();
            if (node->left)
                stc.push(node->left);
            if (node->right)
                stc.push(node->right);
            swap(node->left, node->right);
        }
        return root;
    }
};

Method 3: Traversal with the help of queue sequence: time O(n), space O(n)

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    
    
public:
    TreeNode* mirrorTree(TreeNode* root) 
    {
    
    
        // 3.借助队列:层序遍历
        if (root == nullptr)
            return root;
        queue<TreeNode*> que;
        que.push(root);
        while (!que.empty())
        {
    
    
            TreeNode* node = que.front();
            que.pop();
            if (node->left)
                que.push(node->left);
            if (node->right)
                que.push(node->right);
            swap(node->left, node->right);
        }
        return root;
    }
};

Guess you like

Origin blog.csdn.net/qq_45691748/article/details/113852346