FunctionRacerProblemsRace

Binary Tree Tilt

EasyTreesPython, JavaScript, TypeScript, Java, C++

You are given the root of a binary tree. The tilt of a node is the absolute difference between the sum of all values in its left subtree and the sum of all values in its right subtree (a missing subtree counts as 0). Return the sum of the tilts of every node. An empty tree gives 0.

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 [4,2,9,3,5,null,7]
returns 15

Tilts: 3 -> 0, 5 -> 0, 7 -> 0, 2 -> |3-5| = 2, 9 -> |0-7| = 7, 4 -> |10-16| = 6. Total 15.

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