Monday, June 16, 2014

Print a Binary Tree in Vertical Order


Traversal of tree with level and HashMap>

static void printVerticalOrder(Node root){
if(root == null) return;

HashMap> map = new HashMap>();

printVerticalOrderUtil(root, 0, map);

for(Integer level: map.keySet()){
ArrayList tmp = map.get(level);

for(Integer value: tmp)
System.out.print(value + ",");
System.out.println();
}
System.out.println();
}

private static void printVerticalOrderUtil(Node root, int level,
HashMap> map) {

if(root == null) return;

ArrayList list = (map.get(level) != null)? map.get(level): new ArrayList();
list.add(root.val);

map.put(level, list);

printVerticalOrderUtil(root.left, level-1, map);

printVerticalOrderUtil(root.right, level+1, map);


}


Reference:
http://www.geeksforgeeks.org/print-binary-tree-vertical-order-set-2/

No comments:

Post a Comment