Mid From PDF Coding C# Coding Interview

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:

More from C# Programming Tutorial

All questions for this course
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details