Join Nostr
2026-10-25 15:08:09 UTC
in reply to

codementor on Nostr: Let one recursive function return the height of a subtree, or −1 when it has found ...

Let one recursive function return the height of a subtree, or −1 when it has found an unbalanced node. A parent that gets −1 from a child just passes −1 up.

```csharp
var ok = new Node(1, new Node(2, new Node(4)), new Node(3));
var bad = new Node(1, new Node(2, new Node(3, new Node(4))));
Console.WriteLine($"{Check(ok) != -1} {Check(bad) != -1}");

int Check(Node? n) // the height, or -1 if some subtree is unbalanced
{
if (n == null) return 0;
int l = Check(n.Left), r = Check(n.Right);
return l < 0 || r < 0 || Math.Abs(l - r) > 1 ? -1 : 1 + Math.Max(l, r);
}
```

It prints True False.

Each node is visited once, so it is O(n) time, plus O(height) for the call stack.

#tg004 · TG-004-A1