forked from DengWangBao/Leetcode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInvertBinaryTree.java
47 lines (37 loc) · 1.08 KB
/
InvertBinaryTree.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import java.util.LinkedList;
import java.util.Queue;
/**
* 给非递归法也要会写
* 核心思路就是访问所有的节点,将其左右节点交换,可以采用递归,也可以BFS
*/
public class InvertBinaryTree {
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
TreeNode right = root.right;
root.right = invertTree(root.left);
root.left = invertTree(right);
return root;
}
public TreeNode invertTree2(TreeNode root) {
if (root == null) {
return null;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
TreeNode left = node.left;
node.left = node.right;
node.right = left;
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
return root;
}
}