Payments app~20 min2s · 256 MBtarget O(n) time, O(w) spaceclassic twin: lc-111tree-recursion · bfs
A payments app handles card disputes with a decision tree. Each account of the tree is a question for the support agent, with an answer on the left and one on the right. A question with no answers below it is an outcome, such as refund or reject, marked with a code.
Support wants to know the fewest steps to an outcome, to show it as the best case on a dashboard. The tree can have 100,000 questions, and it can be very deep on one side.
Write shallowest_leaf(values, left, right).
0 to n - 1, and account 0 is the top of the tree. An empty tree has three empty lists.values[i] is the code of account i. left[i] and right[i] are the accounts below it, or -1 where there is none.[0, -1].Input: values = [9, 4, 7, 6, 2, 8, 5, 3], left = [1, 3, 5, 7, -1, -1, -1, -1], right = [2, 4, 6, -1, -1, -1, -1, -1]
Output: [3, 2]The tree has the codes 9 at the top, then 4 and 7, then 6, 2, 8 and 5, and 3 below 6. The account with code 6 has a child, so it is not a leaf.
| Step | Level | Accounts, left to right | Leaf? |
|---|---|---|---|
| [1], [2] | 1 | 9 | no, it has children |
| [3], [4], [2] | 2 | 4, 7 | no, both have children |
| [3], [4], [2] | 3 | 6, 2, 8, 5 | 6 has a child, and 2 is the first leaf |
The answer is [3, 2]. The leaves 8 and 5 are also at depth 3, but 2 is the leftmost of them. The leaf 3 is deeper.
Input: values = [5], left = [-1], right = [-1]
Output: [1, 5]The top is also a leaf, at depth 1.
Input: values = [], left = [], right = []
Output: [0, -1]An empty tree has no leaf.
0 ≤ n ≤ 100,000 and 1 ≤ values[i] ≤ 10^9left and right is -1 or an account number from 1 to n - 10A tree of 100,000 accounts can be a chain, where the only leaf is 100,000 steps down. A walk that goes one branch to its end and compares the paths visits every account.
A walk that goes one level at a time stops at the first leaf. For a tree with a leaf at depth 2, it looks at 3 accounts, however large the tree is.