Niuke.com's sword refers to Offer - the mirror image of the binary tree

Topic description

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

Enter 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

Problem solving ideas

Analyzing the characteristics of these two trees, we can summarize the steps to obtain the mirror image as shown in the following figure.


It can be seen that the steps to find the mirror image are as follows: use the recursive idea to exchange the left and right children of the root node, and then perform the mirror operation on the left child and the right child respectively.

code

/*
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};*/
class Solution {
public:
    void Mirror(TreeNode *pRoot) {
        if( pRoot == NULL )
            return;
        TreeNode* temp = pRoot->left;
        pRoot->left = pRoot->right;
        pRoot->right = temp;
        Mirror(pRoot->left);
        Mirror(pRoot->right);
        
        return;
    }
};

Guess you like

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