Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding the width of a binary tree

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);

    }
like image 571
dojoBeginner Avatar asked May 10 '11 12:05

dojoBeginner


People also ask

What is the width of the tree?

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.

What is width in binary?

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.

What is vertical width of binary tree?

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.


1 Answers

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);
}
like image 116
Robin Green Avatar answered Sep 28 '22 06:09

Robin Green