一、需求
- 请完成一个函数,输入一个二叉树,该函数输出它的镜像。
例如输入:
4
/ \
2 7
/ \ / \
1 3 6 9
镜像输出:
4
/ \
7 2
/ \ / \
9 6 3 1
二、递归法
2.1 思路分析
- 若树为空,直接返回null;
- 定义两个临时变量leftRoot和rightRoot,分别保存当前结点的左结点和右结点;
- 将当前根结点的左结点设置为rightRoot,右结点设置为leftRoot,最后返回root;
- 过程就是从下到上、完成右子树的镜像,然后完成左子树的镜像,最后完成根结点的镜像。
2.2 代码实现
class Solution {
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.3 复杂度分析
- 时间复杂度为O(N),N为二叉树结点的个数,需要遍历所有的结点;
- 最差情况下,二叉树退化为链表,递归时系统需要O(N)大小的栈空间。
三、辅助栈
3.1 思路分析
- 当root为null时,返回null;
- 新建辅助栈,并将根结点入栈;
- 开始循环,当栈不为空时,弹出结点node,添加node的左、右子结点到栈中,交换node的左右子结点;
- 最后返回根结点root。
3.2 代码实现
class Solution {
public TreeNode mirrorTree(TreeNode root) {
if(root == null) return null;
Stack<TreeNode> stack = new Stack<>();
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;
}
}
3.3 复杂度分析
- 时间复杂度为O(N),其中N为二叉树的结点数量,建立二叉树镜像需要遍历二叉树的所有结点,占用O(N)的时间;
- 空间复杂度为O(N),最差情况下,(当为满二叉树时),栈stack最多同时存储(N+1)/2个结点,占用O(N)额外空间。
四、辅助队列
4.1 思路分析
- 思路与辅助栈的相同,不再赘述,下面提供代码部分。
4.2 代码实现
class Solution {
public TreeNode mirrorTree(TreeNode root) {
if(root == null) return null;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while(queue.size() != 0) {
//poll获取失败返回null,remove获取失败抛出异常
TreeNode node = queue.poll();
if(node.left != null) queue.add(node.left);
if(node.right != null) queue.add(node.right);
//交换当前节点下的左右子节点
TreeNode tmp = node.left;
node.left = node.right;
node.right = tmp;
}
return root;
}
}
五、参考地址
作者:Krahets