Thursday, February 6, 2014

Vertical Sum in a given Binary Tree


http://www.geeksforgeeks.org/vertical-sum-in-a-given-binary-tree/


static void verticalSum(Node root) {
if (root == null)
return;
int hd = 0;
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();

verticalSumWrapper(root, hd, map);
if (map != null) {
System.out.println(map.entrySet());
}
}

static void verticalSumWrapper(Node root, int hd, HashMap<Integer, Integer> mp) {
if (root == null)
return;

int tmp = (mp.get(hd) == null) ? 0 : (mp.get(hd));
tmp = tmp + root.data;
mp.put(hd, tmp);

verticalSumWrapper(root.left, hd - 1, mp);

verticalSumWrapper(root.right, hd + 1, mp);

}

No comments:

Post a Comment