import
java.util.LinkedList;
import
java.util.Queue;
class
GFG {
public
static
class
Node {
int
data;
Node left;
Node right;
public
Node(
int
item) {
this
.data = item;
this
.left =
this
.right =
null
;
}
};
public
static
class
Pair {
Node first;
int
second;
public
Pair(Node n,
int
i) {
this
.first = n;
this
.second = i;
}
}
static
int
getMaxWidth(Node root) {
if
(root ==
null
) {
return
0
;
}
Queue<Pair> q =
new
LinkedList<Pair>();
q.add(
new
Pair(root,
0
));
int
maxWidth =
1
;
while
(!q.isEmpty()) {
int
size = q.size();
int
first =
0
, last =
0
;
for
(
int
i =
0
; i < size; i++) {
Node temp = q.peek().first;
int
id = q.peek().second;
q.remove();
if
(i ==
0
) {
first = id;
}
if
(i == size -
1
) {
last = id;
}
;
if
(temp.left !=
null
)
q.add(
new
Pair(temp.left, id *
2
+
1
));
if
(temp.right !=
null
)
q.add(
new
Pair(temp.right, id *
2
+
2
));
}
maxWidth = Math.max(maxWidth, last - first +
1
);
}
return
maxWidth;
}
public
static
void
main(String args[]) {
Node root =
new
Node(
1
);
root.left =
new
Node(
2
);
root.right =
new
Node(
3
);
root.left.left =
new
Node(
4
);
root.left.right =
new
Node(
5
);
root.right.right =
new
Node(
8
);
root.right.right.left =
new
Node(
6
);
root.right.right.right =
new
Node(
7
);
System.out.println(getMaxWidth(root));
}
}