Niuke.com brush questions | mirror image of binary tree

Topic source: Niuke.com
programming connection

Topic description

Operates the given binary tree, transforming it into a mirror image of the source binary tree.
Input description:
Mirror definition of binary tree: source binary tree
8
/ \
6 10
/ \ / \
5 7 9 11
mirror binary tree
8
/ \
10 6
/ \ / \
11 9 7 5

Parse:

Recursive thinking, first the left subtree, count the right subtree, and finally swap the left and right subtrees.

Code:

class Solution {
public:
    void Mirror(TreeNode *pRoot) {
        if(pRoot == nullptr)
            return;
        Mirror(pRoot->left);
        Mirror(pRoot->right);
        auto temp = pRoot->left;
        pRoot->left = pRoot->right;
        pRoot->right = temp;
    }
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325568067&siteId=291194637