-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInvertBinaryTreeIterative.java
More file actions
61 lines (50 loc) · 1.46 KB
/
InvertBinaryTreeIterative.java
File metadata and controls
61 lines (50 loc) · 1.46 KB
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
/**
* Definition for a binary tree node.
* public 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;
* }
* }
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
LinkedList<TreeNode> q = new LinkedList<TreeNode>();
if(root != null){
q.add(root);
}
// Loop till queue is empty...
while(!q.isEmpty()){
// Dequeue front node..
TreeNode node = q.poll();
if(node.left != null){
q.add(node.left);
}
if(node.right != null){
q.add(node.right);
}
TreeNode tmp = node.left;
node.left = node.right;
node.right = tmp;
}
return root;
}
}
/*
Approach: iterative DFS
we add root to queue, and then poll nodes every iteration untill we have some
we process every node in the way that we
1. add left/right childs to queue
2. swap left and right pointers
Thus, due to the FIFO nature of queue we will always move to dephs first,
traversing sub-trees to the deepest left child node
and then moving one level up and processing rigth child node.
Time Complexity: O(n)
Space Complexity: O(n)
*/