【问题描述】[中等]
请完成一个函数,输入一个二叉树,该函数输出它的镜像。例如输入: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]
【解答思路】
1. 递归
时间复杂度:O(N) 空间复杂度:O(N)
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;}
}
public TreeNode mirrorTree(TreeNode root) {if(root == null) return null;TreeNode leftRoot = mirrorTree(root.right);TreeNode rightRoot = mirrorTree(root.left);root.left = leftRoot;root.right = rightRoot;return root;}
2. 辅助栈(或队列)
时间复杂度:O(N) 空间复杂度:O(1)
class Solution {public TreeNode mirrorTree(TreeNode root) {if(root == null) return null;Stack<TreeNode> stack = new Stack<>();stack.add(root);//Stack<TreeNode> stack = new Stack<>() {{ add(root); }};while(!stack.isEmpty()) {TreeNode node = stack.pop();if(node.left != null) stack.add(node.left);if(node.right != null) stack.add(node.right);TreeNode tmp = node.left;node.left = node.right;node.right = tmp;}return root;}
}
【总结】
1.二叉树镜像的定义
2.二叉树常见思路 :递归 栈
3.学习其翻转时暂存变量的思想 递归要有出口
转载;https://leetcode-cn.com/problems/er-cha-shu-de-jing-xiang-lcof/solution/mian-shi-ti-27-er-cha-shu-de-jing-xiang-di-gui-fu-/