leetbook_ioa/docs/LCR 144. 翻转二叉树.md
二叉树镜像定义: 对于二叉树中任意节点 root ,设其左 / 右子节点分别为 left , right ;则在二叉树的镜像中的对应 root 节点,其左 / 右子节点分别为 right , left 。
{:align=center width=450}
根据二叉树镜像的定义,考虑递归遍历(dfs)二叉树,交换每个节点的左 / 右子节点,即可生成二叉树的镜像。
root 为空时(即越过叶节点),则返回 $\text{null}$ ;tmp ,用于暂存 root 的左子节点;mirrorTree(root.right) ,并将返回值作为 root 的 左子节点 。mirrorTree(tmp) ,并将返回值作为 root 的 右子节点 。root ;Q: 为何需要暂存
root的左子节点? A: 在递归右子节点 “root.left = mirrorTree(root.right)” 执行完毕后,root.left的值已经发生改变,此时递归左子节点mirrorTree(root.left)则会出问题。
<,,,,,,,,,,>
class Solution:
def mirrorTree(self, root: TreeNode) -> TreeNode:
if not root: return
tmp = root.left
root.left = self.mirrorTree(root.right)
root.right = self.mirrorTree(tmp)
return root
class Solution {
public TreeNode mirrorTree(TreeNode root) {
if(root == null) return null;
TreeNode tmp = root.left;
root.left = mirrorTree(root.right);
root.right = mirrorTree(tmp);
return root;
}
}
class Solution {
public:
TreeNode* mirrorTree(TreeNode* root) {
if (root == nullptr) return nullptr;
TreeNode* tmp = root->left;
root->left = mirrorTree(root->right);
root->right = mirrorTree(tmp);
return root;
}
};
Python 利用平行赋值的写法(即 a, b = b, a ),可省略暂存操作。其原理是先将等号右侧打包成元组 (b,a) ,再序列地分给等号左侧的 a, b 序列。
class Solution:
def mirrorTree(self, root: TreeNode) -> TreeNode:
if not root: return
root.left, root.right = self.mirrorTree(root.right), self.mirrorTree(root.left)
return root
利用栈(或队列)遍历树的所有节点 node ,并交换每个 node 的左 / 右子节点。
root 为空时,直接返回 $null$ ;root 。stack 为空时跳出;
node ;node 左和右子节点入栈;node 的左 / 右子节点。root 。<,,,,,,,,,,,,,,>
class Solution:
def mirrorTree(self, root: TreeNode) -> TreeNode:
if not root: return
stack = [root]
while stack:
node = stack.pop()
if node.left: stack.append(node.left)
if node.right: stack.append(node.right)
node.left, node.right = node.right, node.left
return root
class Solution {
public TreeNode mirrorTree(TreeNode root) {
if(root == null) return null;
Stack<TreeNode> stack = new 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;
}
}
class Solution {
public:
TreeNode* mirrorTree(TreeNode* root) {
if(root == nullptr) return nullptr;
stack<TreeNode*> stack;
stack.push(root);
while (!stack.empty())
{
TreeNode* node = stack.top();
stack.pop();
if (node->left != nullptr) stack.push(node->left);
if (node->right != nullptr) stack.push(node->right);
TreeNode* tmp = node->left;
node->left = node->right;
node->right = tmp;
}
return root;
}
};
stack 最多同时存储 $\frac{N + 1}{2}$ 个节点,占用 $O(N)$ 额外空间。{:align=center width=450}