The sword refers to the offer (C++)-JZ27: the mirror image of the binary tree (data structure - tree)

Author: Steven Zhai
Copyright Notice: The copyright belongs to the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source

Topic description:

Operates the given binary tree, transforming it into a mirror image of the source binary tree.

Data range: the number of nodes in the binary tree is 0≤n≤1000, and the value of each node in the binary tree is 0≤val≤1000

Requirements: Space complexity O(n). This problem also has in-place operations, that is, the solution of space complexity O(1), time complexity O(n)

for example:

source binary tree

mirror binary tree

Example:

enter:

{8,6,10,5,7,9,11}

return value:

{8,10,6,11,9,7,5}

Problem solving ideas:

This problem examines the use of data structure trees, which can be solved recursively. There are two solutions: one is top-down, starting from the root node, directly exchanging the left and right subtree nodes, and then processing their left and right subtrees respectively, until the deepest layer is completed; the other is bottom-to-bottom. On, after exploring to the deepest level, the left and right subtrees are exchanged, then return to the previous layer, and the left and right are exchanged, and so on. When returning to the root node, the left and right subtrees of the root node are exchanged. when the recursion is completed.

Test code:

Solution 1: Top-down

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pRoot TreeNode类 
     * @return TreeNode类
     */
    TreeNode* Mirror(TreeNode* pRoot) {
        if(!pRoot) return pRoot;
        swap(pRoot->left, pRoot->right);
        Mirror(pRoot->left);
        Mirror(pRoot->right);
        return pRoot;
    }
};

 Solution 2: Bottom-up

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pRoot TreeNode类 
     * @return TreeNode类
     */
    TreeNode* Mirror(TreeNode* pRoot) {
        if(!pRoot) return NULL;
        TreeNode* left = Mirror(pRoot->left);
        TreeNode* right = Mirror(pRoot->right);
        pRoot->left = right;
        pRoot->right = left;
        return pRoot;
    }
};

Guess you like

Origin blog.csdn.net/zhaitianbao/article/details/122860148