563 Binary Tree Tilt
Given a binary tree, return the tilt of thewhole tree.
The tilt of atree nodeis defined as theabsolute differencebetween the sum of all left subtree node values and the sum of all right subtree node values. Null node has tilt 0.
The tilt of thewhole treeis defined as the sum of all nodes' tilt.
Example:
Input:
1
/ \
2 3
Output:
1
Explanation:
Tilt of node 2 : 0
Tilt of node 3 : 0
Tilt of node 1 : |2-3| = 1
Tilt of binary tree : 0 + 0 + 1 = 1Note:
The sum of node values in any subtree won't exceed the range of 32-bit integer.
All the tilt values won't exceed the range of 32-bit integer.
Performance: O(N) time and space
The Idea: Because summations are have the property to be associative, we can use dynamic programming to first build a accumulation tree. With accumulation trees, every node is the summation of itself and its left and right subtrees. Using post order traversal, we can achieve this is O(N) time. Next, iterating through this accumation tree, we do another post order traversal that accumulations the absolute difference between the left and right subtrees. This also runs in O(N) time because the accumulation tree provides the summation of the left and right subtrees.
Some helpful debugging code:
Last updated
Was this helpful?