Sword refers to the mirror image of offer acwing 38 binary tree

Topic

Insert picture description here

Topic

From our observation, we can find that all the child nodes have exchanged positions, so we only need to recurse from the root node, and then exchange the left and right sons of the root node.

Code

/**
 * 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:
    void mirror(TreeNode* root) {
    
    
        if(!root) return;
        mirror(root->left);
        mirror(root->right);
        swap(root->left,root->right);
    }
};

Guess you like

Origin blog.csdn.net/qq_44791484/article/details/115037684