18. 二叉树的镜像
题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。
输入描述:
二叉树的镜像定义:源二叉树 8 / 6 10 / / 5 7 9 11 镜像二叉树 8 / 10 6 / / 11 9 7 5
法一:使用递归
如果结点为空,直接返回,否则递归交换每个结点的左右子树
1 public class Solution { 2 // 递归交换每个结点的左右子树 3 public void Mirror(TreeNode root) { 4 if(root == null){ 5 return ; 6 } 7 // 交换左右子树 8 TreeNode temp = root.left; 9 root.left = root.right; 10 root.right = temp; 11 // 递归交换左右子树 12 Mirror(root.left); 13 Mirror(root.right); 14 } 15 }
复杂度分析:
时间复杂度:每个结点均会被递归访问一次,所以时间复杂度为O(n)
空间复杂度:递归栈的最大深度为树的高度,所以空间复杂度为O(logn)
法二:利用层序遍历树
访问结点时候交换左右子树,然后左右子树入队
1 import java.util.Queue; 2 public class Solution { 3 public void Mirror(TreeNode root) { 4 if(root == null){ 5 return; 6 } 7 8 // 层序遍历 9 Queue<TreeNode> Q = new LinkedList<>(); 10 Q.offer(root); 11 while(!Q.isEmpty()){ 12 // 出队队首元素 13 TreeNode node = Q.poll(); 14 // 交换左右子树 15 TreeNode temp = node.left; 16 node.left = node.right; 17 node.right = temp; 18 // 如果孩子不为空,入队 19 if(node.left != null) 20 Q.offer(node.left); 21 if(node.right != null) 22 Q.offer(node.right); 23 } 24 } 25 }
牛客网的在线编辑器用使用 Queue 必须手动导包 import java.util.Queue;
leetcode 运行时间为0ms, 空间为36.2mb
复杂度分析:
时间复杂度:每个结点入队出队一次,所以时间复杂度为O(n)
空间复杂度:队列中结点个数最多为树的一层结点的个数,所以空间复杂度也为O(n)