27 二叉树的镜像
递归
使用递归的思想。首先交换根节点的左右子树,然后继续对根节点的左右子树进行镜像反转。具体看代码。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode mirrorTree(TreeNode root) {
if(root == null){
return null;
}
TreeNode new_left = mirrorTree(root.right);
TreeNode new_right = mirrorTree(root.left);
root.left=new_left;
root.right = new_right;
return root;
}
}
非递归 -1
使用后序遍历非递归的框架,在应该输出节点的地方交换左右子树。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode mirrorTree(TreeNode root) {
if(root == null){
return root;
}
Stack<TreeNode> s = new Stack<>();
TreeNode pCur = root;
TreeNode pLast = null;
while(pCur != null){
s.push(pCur);
pCur = pCur.left;
}
while(!s.empty()){
pCur = s.peek();
s.pop();
if(pCur.right == pLast || pCur.right == null){
if(pCur.right==null && pCur.left==null){
pLast = pCur;
}
TreeNode tmp = pCur.right;
pCur.right = pCur.left;
pCur.left = tmp;
pLast = pCur;
}else{
s.push(pCur);
pCur = pCur.right;
while(pCur != null){
s.push(pCur);
pCur = pCur.left;
}
}
}
return root;
}
}
非递归 -2
利用栈遍历树的所有节点,并交换每个节点的左/右子节点。
算法流程:
- 特例处理:当 root 为空时,直接返回 null;
- 初始化:栈初始化,并加入根节点 root
- 循环:当栈为空时跳出循环;
- 出栈:记为 p C u r pCur pCur
- 添加子节点:将 p C u r pCur pCur的左右子节点加入栈
- 交换:交换 p C u r pCur pCur的左右子节点。
- 返回值;返回根节点 root。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode mirrorTree(TreeNode root) {
if(root == null){
return null;
}
Stack<TreeNode> s = new Stack<>();
TreeNode pCur = null;
TreeNode left = null;
TreeNode right = null;
s.push(root);
while(!s.empty()){
pCur = s.peek();
s.pop();
left = pCur.left;
right = pCur.right;
//左右子节点入栈
if(left != null){
s.push(left);
}
if(right != null){
s.push(right);
}
//交换左右子节点
pCur.left = right;
pCur.right = left;
}
return root;
}
}
时间复杂度:
O
(
n
)
O(n)
O(n),其中
n
n
n是二叉树的节点数量,建立二叉树镜像需要遍历树的所有节点,占用
O
(
n
)
O(n)
O(n)时间。
空间复杂度:
O
(
n
)
O(n)
O(n),最差的情况,栈最多同时存储
n
+
1
2
\frac{n+1}{2}
2n+1个节点,占用
O
(
n
)
O(n)
O(n)额外空间。