1、题目描述

2、算法分类 ---- 搜索与回溯
【搜索与回溯】是计算机解题中常用的算法,很多问题无法根据某种确定的计算法则来求解,可以利用搜索与回溯的技术求解。它的基本思想是:为了求得问题的解,先选择某一种可能情况向前探索,在探索过程中,一旦发现原来的选择是错误的,就退回一步重新选择,继续向前探索,如此反复进行,直至得到解或证明无解。
3、代码实现--方法一【递归与回溯】
- class Solution {
-
- //方法一:
- public TreeNode mirrorTree(TreeNode root){
- if(root == null) return null;
-
- //进行交换
- TreeNode tempNode = root.left;
- root.left = root.right;
- root.right = tempNode;
-
- //进行递归
- mirrorTree(root.left);
- mirrorTree(root.right);
- return root;
- }
- }
时间复杂度 O(N) : 其中 N 为二叉树的节点数量,建立二叉树镜像需要遍历树的所有节点,占用 O(N)时间。
空间复杂度 O(N): 最差情况下(当二叉树退化为链表),递归时系统需使用 O(N)大小的栈空间。
4、代码实现--方法二【辅助栈 / 队列】
- class Solution {
- public TreeNode mirrorTree(TreeNode root){
- if(root == null) return null;
-
- //镜像是反向输出,因此用的Stack栈模式
- Stack<TreeNode> stack = new Stack<TreeNode>();
- 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 tempNode = node.left;
- node.left = node.right;
- node.right = tempNode;
- }
- return root;
- }
- }
时间复杂度 O(N) : 其中 N 为二叉树的节点数量,建立二叉树镜像需要遍历树的所有节点,占用 O(N)时间。
空间复杂度 O(N) : 如下图所示,最差情况下,栈 stack 最多同时存储 (N+1 / 2 )个节点,占用 O(N) 额外空间