-
-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathInvertBinaryTree226.java
84 lines (63 loc) · 1.55 KB
/
InvertBinaryTree226.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package easy;
import java.util.LinkedList;
import java.util.Queue;
public class InvertBinaryTree226 {
private class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public TreeNode invertTree(TreeNode root) {
if (root == null)
return null;
// inverting the subtree first
TreeNode leftSubtree = invertTree(root.left);
TreeNode rightSubtree = invertTree(root.right);
// now swaping the root left and right subtree
root.left = rightSubtree;
root.right = leftSubtree;
return root;
}
public TreeNode invertTree2(TreeNode root) {
if (root == null)
return null;
// swap left & right subtree
TreeNode tempnode = root.left;
root.left = root.right;
root.right = tempnode;
// recursively solve for children
invertTree(root.left);
invertTree(root.right);
return root;
}
public TreeNode invertTreeIterative(TreeNode root) {
if (root == null)
return null;
// bfs approach
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
while (!queue.isEmpty()) {
// remove from queue and swap children
TreeNode currentNode = queue.poll();
// swap
TreeNode temp = currentNode.left;
currentNode.left = currentNode.right;
currentNode.right = temp;
if (currentNode.left != null)
queue.add(currentNode.left);
if (currentNode.right != null)
queue.add(currentNode.right);
}
return root;
}
}