Refer : http://www.geeksforgeeks.org/archives/18215
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Set;
import java.util.Iterator;
public class VerticalSumInTree {
public static void main(String[] args) {
Node root = getTree();
printVertcalSumsInTree(root);
}
private static Node getTree() {
Node node4 = new Node(4);
Node node5 = new Node(5);
Node node6 = new Node(6);
Node node7 = new Node(7);
Node node2 = new Node(2, node4, node5);
Node node3 = new Node(3, node6, node7);
Node root = new Node(1, node2, node3);
return root;
}
private static void printVertcalSumsInTree(Node root) {
if (root == null)
return;
// Used for storing nodes matches to same horizontal distance
Map<Integer, List<Node>> map = new HashMap<Integer, List<Node>>();
calculateVerticalSum(root, map, 0);
printVerticalSums(map);
}
private static void printVerticalSums(Map<Integer, List<Node>> map) {
if (map == null) {
System.out.println("Tree is empty");
} else {
Set<Integer> keys = map.keySet();
// Sort the keys
// convert set to list for sorting.Because collections accepts list
// for sorting
List<Integer> keysList = new ArrayList<Integer>(keys);
Collections.sort(keysList);
// For each key, get the list of values
for (Integer key : keysList) {
List<Node> list = map.get(key);
// Iterate through the list elements and calculate the sum
int sum = 0;
Iterator<Node> it = list.iterator();
while (it.hasNext()) {
Node n = it.next();
sum = sum + n.value;
}
System.out.println(sum);
}
}
}
private static void calculateVerticalSum(Node root,
Map<Integer, List<Node>> map, int horizontalDistance) {
if (root == null)
return;
// Add this value to the map
List<Node> list = map.get(horizontalDistance);
if (list == null) {
list = new ArrayList<Node>();
}
list.add(root);
map.put(horizontalDistance, list);
// iterate for left and right trees
calculateVerticalSum(root.left, map, horizontalDistance - 1);
calculateVerticalSum(root.right, map, horizontalDistance + 1);
}
public static class Node {
public int value;
// member variables will be initialized to null by default.
public Node left;
public Node right;
public Node(int value) {
this.value = value;
}
public Node(int value, Node left, Node right) {
this.value = value;
this.left = left;
this.right = right;
}
}
}
No comments:
Post a Comment