Binary Tree Tilt

EasyTreesdfs

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

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 has sum 0, so a leaf has tilt 0. Given the root of a binary tree, return the sum of the tilts of **every** node. An empty tree has total tilt 0. Computing subtree sums bottom-up lets you do this in a single O(n) post-order pass.

Examples

Input: root = [1,2,3]
Output: 1
The leaves have tilt 0; the root has tilt |2 - 3| = 1.
Input: root = [4,2,9,3,5,null,7]
Output: 15
Tilts: 3->0, 5->0, 7->0, 2->|3-5|=2, 9->|0-7|=7, 4->|10-16|=6. Total 15.

Constraints

  • 0 <= number of nodes <= 10^4
  • -1000 <= Node.val <= 1000

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More dfs problems