|
|
@ -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<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 temp = node.left; |
|
|
|
|
|
|
|
node.left = node.right; |
|
|
|
|
|
|
|
node.right = temp; |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
return root; |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
``` |
|
|
|
|
|
|
|
|
|
|
|