21 Dec 2013

Trees: Median At Given Level in a Binary Tree

Problem Statement: 
        Find the Median at a given level (say level 3) in a binary Tree.

Fig: Given Binary Tree

Output: For level 3
 Available Nodes @ given Level : [4, 5, 6, 7]  
 Median : 6  

Solution:

Full Source Code: LINK

Code snippet for the logic involved.


 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
/**
  * Subroutine to calculate median
  * @param level : Given level
  * @return : median
  */
 public Node medianAtLevelK(Node root, int level){
  List<Node> list = itemsAtLevelK(root,level,new ArrayList<Node>());
  Node median = list.get(list.size()/2);
  System.out.println("Available Nodes @ given Level : " + list);
  System.out.println("Median : " +median);
  return median;
 }

 /**
  * Fills the list with items at given level
  * @return list filled with nodes at the prescibed level
  */
 public List<Node> itemsAtLevelK(Node root,int level, List<Node> list){
  if(root == null)
   return list;

  if(level == 1)
   list.add(root);

  list=itemsAtLevelK(root.left, level-1,list);
  list=itemsAtLevelK(root.right, level-1,list);

  return list;
 }


Please post your suggestions and comments.
Happy Coding!!:)

No comments:

Post a Comment