17、二叉树的镜像
请完成一个函数,输入一个二叉树,该函数输出它的镜像。
例如输入:
4 / \ 2 7 / \ / \ 1 3 6 9
镜像输出:
4 / \ 7 2 / \ / \ 9 6 3 1
示例 1:
输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]
限制:
0 <= 节点个数 <= 1000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/er-cha-shu-de-jing-xiang-lcof
思路:
这题的思路很简单,直接从根节点出发,每次交换左右儿子即可,然后递归左右子树。因为子树也要镜像嘛。
图解:
代码实现:
/**
* 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) return NULL;
swap(root->left, root->right); //交换左右儿子
mirrorTree(root->left); //递归左子树
mirrorTree(root->right); //递归右子树
return root;
}
};