Update 二叉树相关.md

master
Omooo 4 years ago
parent 6e6883bff3
commit 735e340575
  1. 44
      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<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;
}
}
```

Loading…
Cancel
Save