题目:
请完成一个函数,输入一个二叉树,该函数输出它的镜像。
示例 1:
输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]
方法1、递归
递归三要素:
- 终止条件:当root==null的时候return null
- 返回值:显然是返回二叉树的镜像的根节点
- 函数的意义:函数实参是一个二叉树的根节点,中间语句是构建其镜像,然后返回根节点
那么就是说,mirrorTree(root.left)是左子树的镜像,mirrorTree(roo.right)是右子树的镜像,然后将root的左右子节点交换位置即可
代码如下:
/**
* 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 left = mirrorTree(root.left);
TreeNode right = mirrorTree(root.right);
root.left = right;
root.right = left;
return root;
}
}
方法二、辅助栈
显然只要每个节点的左右子节点交换即可得到其镜像。
代码如下:
/**
* 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;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode node = stack.pop();
if (node.left!=null){
stack.push(node.left);
}
if (node.right!=null){
stack.push(node.right);
}
TreeNode temp = node.left;
node.left = node.right;
node.right = temp;
}
return root;
}
}