题目:请完成一个函数,请函数输出它的镜像
例如:
思路:看见此题目首先想到的应该是二叉树的层次遍历,而且是反向的。但是希望的是在函数结束之后,只返回根节点,就可实现这样的效果,那么我们就不能当做简单的遍历了,我们需要在原二叉树上交换各个节点的左右孩子。因此这道题可以用递归解决
代码实现:
/**
* 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:
TreeNode* mirrorTree(TreeNode* root) {
if(root == NULL) return root;
TreeNode* tmp = root->left;//这里必须改变指针的指向,不能简单的只改变值
root->left = root->right;
root->right = tmp;
mirrorTree(root->left);
mirrorTree(root->right);
return root;
}
};