Problem 409
Binary Tree Tilt
Easy · 10 pts · Tree, Depth-First Search, Binary Tree
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. The tilt of the whole tree is the sum of the tilts of all its nodes. Compute it with one post-order traversal that returns each subtree's sum while adding up the tilts.
Input
The first line contains N, the number of tokens. The second line contains N tokens describing the tree in level order (breadth-first, left to right), where 'null' marks a missing child, as on LeetCode.
Output
Print the total tilt of the tree.
Constraints
1 <= number of nodes <= 10000; -1000 <= value <= 1000
Example input
3 1 2 3
Example output
1
Explanation
In the tree 1 / 2 3, the leaves have tilt 0 and the root has tilt |2 - 3| = 1, so the total tilt is 1.