Dsa
Trees
Medium
The Balanced Cargo Tree
In a binary cargo tree, each node carries a specific weight. A node is 'unbalanced' if the total weight of its left subtree and the total weight of its right subtree differ by more than a given threshold X. Total weight of a subtree is the sum of weights of all nodes in that subtree. Given the tree and X, count how many nodes in the tree are unbalanced.
Input Format:
Line 1: N X (number of nodes and threshold)
Line 2: N integers (weights of nodes 0 to N-1)
Next N-1 lines: u v side (u is parent, v is child, side is 0 for left, 1 for right)
Example:
Input:
3 10
100 50 50
0 1 0
0 2 1
Output:
0
Key concepts
post-order traversalsubtree sumtree recursion
Practise this out loud — free
Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.
🎙 Practise this question now