Finding the width of binary tree.
In my code for each leave i create a entry in a hash map and keep updating it when i found a node at leave i.Finally i will iterate the hashmap to find max width.But how can i do it without using any classleel/global varaiables?
Map<Integer,Integer> mp = new HashMap<Integer,Integer>();
void width(Node node,int level){
if(node==null)
return;
if(mp.containsKey(level)){
int count = mp.get(level);
mp.put(level, count+1);
}else{
mp.put(level, 1);
}
width(node.left, level+1);
width(node.right, level+1);
}
The width of a tree for any level is defined as the number of nodes between the two extreme nodes of that level including the NULL node in between. Therefore, the maximum width of the tree is the maximum of all the widths i.e., max{1, 2, 4, 2} = 4.
The width of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes that would be present in a complete binary tree extending down to that level are also counted into the length calculation.
The width of a binary tree is the number of vertical paths in the Binary tree. Explanation: In this image, the tree contains 6 vertical lines which are the required width of the tree.
Just create the HashMap inside the method, then move all the work into an auxillary method, like this:
void width(Node node,int level){
Map<Integer,Integer> mp = new HashMap<Integer,Integer>();
widthImpl(mp, node, level);
// find maximum
}
private void widthImpl(Map<Integer,Integer> mp, Node node, int level) {
if(node==null)
return;
if(mp.containsKey(level)){
int count = mp.get(level);
mp.put(level, count+1);
}else{
mp.put(level, 1);
}
widthImpl(mp, node.left, level+1);
widthImpl(mp, node.right, level+1);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With