二叉树的镜像(剑指Offer-27)
题面
请完成一个函数,输入一个二叉树,该函数输出它的镜像。
例如输入:
1 4 2 / \ 3 2 7 4 / \ / \ 51 3 6 9
镜像输出:
1 4 2 / \ 3 7 2 4 / \ / \ 59 6 3 1
示例
1输入:root = [4,2,7,1,3,6,9]
2输出:[4,7,2,9,6,3,1]
限制
10 <= 节点个数 <= 1000
思路
递归。
代码
1/**
2 * Definition for a binary tree node.
3 * struct TreeNode {
4 * int val;
5 * TreeNode *left;
6 * TreeNode *right;
7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8 * };
9 */
10class Solution {
11public:
12 TreeNode* mirrorTree(TreeNode* root) {
13 if(root==NULL) return NULL;
14 TreeNode *t = root->left;
15 root->left = mirrorTree(root->right);
16 root->right = mirrorTree(t);
17 return root;
18 }
19};