FunctionRacerProblemsRace

Column Sums of a Binary Tree

EasyTreesPython, JavaScript, TypeScript, Java, C++

You are given the root of a binary tree. Give every node a column: the root is column 0, a left child is one column to the left of its parent (parent minus 1) and a right child one to the right (parent plus 1). Add up the values of all nodes in each column and return the sums from the leftmost column to the rightmost. An empty tree gives [].

Trees appear in the tests in level order, with null for a missing child, like [3,9,20,null,null,15,7]. Each node is a TreeNode with .val, .left and .right; the class is already defined for you.

Example 1

root [1,2,3,4,5,6,7]
returns [4,2,12,3,7]

Columns -2..2 have sums 4, 2, 1+5+6 = 12, 3, 7.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Trees problems