## Sword refers to Offer27-mirror of binary tree-easy

#### Title description:

Please complete a function, input a binary tree, and the function outputs its mirror image.

For example, enter:

``````     4
/   \
2     7
/ \   / \
1   3 6   9
``````

Mirror output:

``````     4
/   \
7     2
/ \   / \
9   6 3   1
``````

#### Test case:

``````输入：root = [4,2,7,1,3,6,9]

``````

#### data range:

``````0 <= 节点个数 <= 1000
``````

#### Problem-solving ideas:

1. dfs, depth first search.
2. The search order is the left subtree first, then the right subtree. Finally swap the left and right subtrees
3. The recursive exit is a non-leaf node, just return.

#### AC code (c++)

``````/**
* 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 dfs(TreeNode* root){

if(root == NULL){

return ;
}
dfs(root->left);
dfs(root->right);
TreeNode * tmp = root->left;
root->left = root->right;
root->right = tmp;
}
TreeNode* mirrorTree(TreeNode* root) {

dfs(root);
return root;
}
};
``````

### Guess you like

Origin blog.csdn.net/Yang_1998/article/details/113036858
Recommended
Ranking
Daily