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]
输出:[4,7,2,9,6,3,1]
data range:
0 <= 节点个数 <= 1000
Problem-solving ideas:
- dfs, depth first search.
- The search order is the left subtree first, then the right subtree. Finally swap the left and right subtrees
- 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;
}
};