Check if Binary tree is Sum tree or not
Pattern: Tree DP basics
In a sum tree, every non-leaf node equals the sum of all values in its left and right subtrees; leaves (and an empty tree) are fine. Return each subtree's total from a post-order pass, or a marker as soon as the rule breaks.
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
Return whether every non-leaf node's value equals the sum of all values in its two subtrees. Leaves and an empty tree
count as sum trees. [3, 1, 2] is true. The catalogue has no practice link for this one. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.
Think first
- What must each internal node equal?
- What do you need from each child?
- How can one function return both a total and a failure?
Hints
Brute force, and why it fails
Compute subtree sums from scratch at each node: O(n²).
The key insight
If the rule holds below, a node's subtree total is just 2 × its value (for internal nodes), and one post-order pass checks everything.
Dry run
| left | 20 |
|---|---|
| right | 6 |
Tree [26, 10, 3, 4, 6, null, 3]. 10 = 4 + 6: fine, total 20. 3 = 3: fine, total 6.
The plan
sum(n): if null: 0; if leaf: n.val
l = sum(left); r = sum(right)
if a marker came back or n.val != l + r: return marker
return n.val + l + r
Complexity
- Time
O(n)- Space
O(h)
One post-order pass.
Edge cases
- Empty: true.
- A single leaf: true.
- All zeros: true.
I've built my logic, show the code
Java
class Solution {
public boolean isSumTree(TreeNode root) {
return sum(root) != Integer.MIN_VALUE;
}
private int sum(TreeNode n) { // the subtree's total, or MIN_VALUE if it breaks the rule
if (n == null) return 0;
if (n.left == null && n.right == null) return n.val; // a leaf is fine
int l = sum(n.left), r = sum(n.right);
if (l == Integer.MIN_VALUE || r == Integer.MIN_VALUE || n.val != l + r) return Integer.MIN_VALUE;
return n.val + l + r;
}
}C++
class Solution {
public:
bool isSumTree(TreeNode* root) {
return sum(root) != LLONG_MIN;
}
long long sum(TreeNode* n) { // the subtree's total, or LLONG_MIN if it breaks the rule
if (n == NULL) return 0;
if (n->left == NULL && n->right == NULL) return n->val; // a leaf is fine
long long l = sum(n->left), r = sum(n->right);
if (l == LLONG_MIN || r == LLONG_MIN || n->val != l + r) return LLONG_MIN;
return n->val + l + r;
}
};Python
class Solution:
def isSumTree(self, root) -> bool:
def total(n): # the subtree's total, or None if it breaks the rule
if n is None:
return 0
if not n.left and not n.right:
return n.val # a leaf is fine
l, r = total(n.left), total(n.right)
if l is None or r is None or n.val != l + r:
return None
return n.val + l + r
return total(root) is not NoneCommon mistakes
- Comparing with the children's values instead of their subtree totals.
- Treating leaves as failing.