🌕 剑指 Offer 27. 二叉树的镜像
2022年10月10日
- algorithm
🌕 剑指 Offer 27. 二叉树的镜像
难度: 🌕
问题描述
解法 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) {
// 思路:
// 迭代
mySol(root);
return root;
}
private void mySol(TreeNode root) {
// 递归终止条件
if(root == null) {
return;
}
// root != null
TreeNode left = root.left;
TreeNode right = root.right;
root.left = right;
root.right = left;
mySol(root.left);
mySol(root.right);
}
}
输出 1
解法 2 - 迭代
/**
* 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;
}
LinkedList<TreeNode> stack = new LinkedList<>();
stack.push(root);
while(!stack.isEmpty()) {
TreeNode cur = stack.pop();
TreeNode left = cur.left;
TreeNode right = cur.right;
cur.left = right;
cur.right = left;
if(cur.left != null) {
stack.push(cur.left);
}
if(cur.right != null) {
stack.push(cur.right);
}
}
return root;
}
}