题目:输入一个二叉树,该函数输出它的镜像。
看题第一思路
- I(input):root=[4,2,7,1,3,6,9] O(output):root=[4,7,2,9,6,3,1]
- 第一感觉便是用递归思想解决这个问题,
0<=节点个数<=1000
需要注意的是node=0
时返回的是null
,node=1
时返回的是root
,其他情况即正常操作即可。 - 输出镜像即为递归地交换左右子树,按照交换两个数字的思路写代码即可。
递归——深度优先
- 代码
class Solution {
public TreeNode mirrorTree(TreeNode root) {
if(root==null)
return null;
if(root.left!=null || root.right!=null) {
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
}
mirrorTree(root.left);
mirrorTree(root.right);
/* 可简化:
if(root == null) return null;
TreeNode tmp = root.left;
root.left = mirrorTree(root.right);
root.right = mirrorTree(tmp);
*/
return root;
}
}
- 时间复杂度: O(N),其中N为二叉树的节点数量,建立二叉树镜像需要遍历树的所有节点,占用 O(N)时间。
- 空间复杂度: O(N),最差情况下(即二叉树退化为链表),递归时需使用O(N)大小的栈空间。
- 运行结果
辅助栈/队列——广度优先
- 思路:
初始化一个辅助队列,用来存储树节点,当队列不为空时,队首出队列,将其左右子树交换后按照从左到右的顺序入队列,直到队列为空。 - 代码
public TreeNode mirrorTree(TreeNode root) {
if(root==null) return null;
Queue<TreeNode> que = new LinkedList<TreeNode>();
que.add(root);
while(!que.isEmpty()) {
TreeNode node = que.remove();
TreeNode tmp = node.left;
node.left = node.right;
node.right = tmp;
if(node.left!=null) que.add(node.left);
if(node.right!=null) que.add(node.right);
}
return root;
}
- 时间、空间复杂度同上