forked from GDSC-IGDTUW-Autumn-of-Code-2022/dsa-foundation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MaxWidthOfBinaryTree.java
62 lines (55 loc) · 1.66 KB
/
MaxWidthOfBinaryTree.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
import java.util.*;
class TreeNode {
int data;
TreeNode left, right;
TreeNode(int data)
{
this.data=data;
left=null;
right=null;
}
}
class Pair {
TreeNode node;
int num;
Pair(TreeNode _node, int _num) {
num = _num;
node = _node;
}
}
class MaxWidthOfBinaryTree {
public static int widthOfBinaryTree(TreeNode root) {
if(root == null) return 0;
int ans = 0;
Queue<Pair> q = new LinkedList<>();
q.offer(new Pair(root, 0));
while(!q.isEmpty()){
int size = q.size();
int mmin = q.peek().num; //to make the id starting from zero
int first = 0,last = 0;
for(int i=0; i<size; i++){
int cur_id = q.peek().num-mmin;
TreeNode node = q.peek().node;
q.poll();
if(i==0) first = cur_id;
if(i==size-1) last = cur_id;
if(node.left != null)
q.offer(new Pair(node.left, cur_id*2+1));
if(node.right != null)
q.offer(new Pair(node.right, cur_id*2+2));
}
ans = Math.max(ans, last-first+1);
}
return ans;
}
public static void main(String args[]) {
TreeNode root = new TreeNode(1);
root . left = new TreeNode(3);
root.right = new TreeNode(2);
root . left . left = new TreeNode(5);
root . left . right = new TreeNode(3);
root . right . right = new TreeNode(9);
int maxWidth = widthOfBinaryTree(root);
System.out.println("The maximum width of the Binary Tree is "+maxWidth);
}
}