diff --git a/blogs/Algorithm/剑指 Offer/二叉树相关.md b/blogs/Algorithm/剑指 Offer/二叉树相关.md index 302243d..192bd39 100644 --- a/blogs/Algorithm/剑指 Offer/二叉树相关.md +++ b/blogs/Algorithm/剑指 Offer/二叉树相关.md @@ -89,3 +89,47 @@ class Solution { } ``` +#### [ 27. 二叉树的镜像](https://leetcode-cn.com/problems/er-cha-shu-de-jing-xiang-lcof/) + +```java +class Solution { + + public TreeNode mirrorTree(TreeNode root) { + if (root == null) { + return null; + } + TreeNode rootLeft = mirrorTree(root.right); + TreeNode rootRight = mirrorTree(root.left); + root.left = rootLeft; + root.right = rootRight; + return root; + } +} +``` + +```java +class Solution { + + public TreeNode mirrorTree(TreeNode root) { + if (root == null) { + return null; + } + Stack 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 temp = node.left; + node.left = node.right; + node.right = temp; + } + return root; + } +} +``` +