1.问题描述
2.问题分析
参考题解面试题27. 二叉树的镜像(递归 / 辅助栈,清晰图解)
使用递归的方法:根据二叉树镜像的定义,考虑递归遍历(dfs)二叉树,交换每个节点的左 / 右子节点,即可生成二叉树的镜像。
递归解析:
终止条件: 当节点 root 为空时(即越过叶节点),则返回 null ;
递推工作:
初始化节点 tmp ,用于暂存 root 的左子节点;
开启递归 右子节点 mirrorTree(root.right) ,并将返回值作为 root 的 左子节点 。
开启递归 左子节点 mirrorTree(tmp) ,并将返回值作为 root 的 右子节点 。
返回值: 返回当前节点 root ;
3.代码实现
3.1C++代码
/**
* 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 NULL;
TreeNode *temp=root->left;
root->left=mirrorTree(root->right);
root->right=mirrorTree(temp);
return root;
}
};
3.2Java代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode mirrorTree(TreeNode root) {
if(root == null) return null;
TreeNode tmp = root.left;
root.left = mirrorTree(root.right);
root.right = mirrorTree(tmp);
return root;
}
}