1636. Fairest Cut

Medium3.5 points estimatedBinary TreeDepth-First SearchTree

A rope-bridge network is shaped like a binary tree and every node carries a weight, which may be negative. You must cut exactly one edge, which splits the tree into two separate parts.

The imbalance of a cut is the absolute difference between the total weight of one part and the total weight of the other. Given root, return the smallest imbalance over all possible single-edge cuts, as a long.

The tree has at least two nodes, so at least one edge exists. Each cut detaches the subtree of one non-root node: if T is the total weight and S the weight of that subtree, the imbalance is |T - 2S|. Solve it in one pass in O(n) time and O(n) space; the tree can be a long chain, so use an iterative traversal instead of deep recursion.

Example 1

Input:
root = [3,1,2]
Output:
2
Explanation:

Total is 6; cutting off the node 1 leaves parts 1 and 5 (difference 4), cutting off 2 leaves 2 and 4 (difference 2).

Example 2

Input:
root = [10,-4,6,null,5]
Output:
5
Explanation:

The total is 17; cutting off the node 6 gives parts 6 and 11 (difference 5), which beats every other cut.

Example 3

Input:
root = [-7,-7]
Output:
0
Explanation:

The two parts are -7 and -7, so the difference is 0.

Constraints

2 ≤ nodes ≤ 105

-104 ≤ Node.val ≤ 104

generated trees shape random (iterative traversal advised)

recomputing sums per edge is O(n^2)

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…