-
-
Notifications
You must be signed in to change notification settings - Fork 155
Expand file tree
/
Copy pathInvertTree.java
More file actions
49 lines (34 loc) · 923 Bytes
/
Copy pathInvertTree.java
File metadata and controls
49 lines (34 loc) · 923 Bytes
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
48
49
package leetcode.easy;
import util.TreeNode;
import java.util.LinkedList;
import java.util.Queue;
public class InvertTree {
TreeNode invertTreeRecursive(TreeNode root) {
if (root == null)
return null;
TreeNode temp = root.right;
root.right = root.left;
root.left = temp;
invertTree(root.left);
invertTree(root.right);
return root;
}
TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
final Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
final TreeNode node = queue.poll();
// Swap nodes
final TreeNode temp = node.left;
node.left = node.right;
node.right = temp;
// Add left and right of this node to the queue
if (node.left != null) queue.add(node.left);
if (node.right != null) queue.add(node.right);
}
return root;
}
}