Find the vertical sum of a binary tree?
void VerticalSum(TreeNode root, int hd, Dictionary<int, int> map) {
if (root == null) return;
VerticalSum(root.left, hd - 1, map);
if (map.ContainsKey(hd))
map[hd] += root.val;
else
map[hd] = root.val;
VerticalSum(root.right, hd + 1, map);
Dictionary<int, int> GetVerticalSum(TreeNode root) {
var map = new Dictionary<int, int>();
VerticalSum(root, 0, map);
return map;
Explanation:
Use horizontal distance (hd) from root; sum values of nodes at each hd.
Follow on: