Social feed~40 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-297tree-recursion
A social feed shows a reply thread as a tree. Each message has a reaction score, which can be negative, and up to two direct replies: a left reply and a right reply. Before an update, a job saves the thread as one line of text. After the update, another job loads the thread back from that text alone.
You write both jobs. The thread can hold up to 200,000 messages, and different messages can have the same score.
Write save_and_load_tree(values, left, right).
0 to n - 1, and message 0 is the first message, the root. values[i] is the score of message i.left[i] and right[i] are the numbers of the replies to message i, or -1 where there is none. The thread is a binary tree, and the scores follow no order.# in place of every missing reply, for every message in the tree.# for a missing reply of a message that is in the tree, and drop every # at the end.# and loaded as the empty text.Input: values = [12, 5, -4, 8, 3], left = [1, 3, -1, -1, -1], right = [2, -1, 4, -1, -1]
Output: ["12,5,8,#,#,#,-4,#,3,#,#", "12,5,-4,8,#,#,3"]The save writes 12, then its left subtree 5, 8 with its three marks, then its right subtree -4, 3 with its marks. Loading reads the 11 tokens in order and keeps a stack of the messages that still wait for a reply.
| Token read | It becomes | Waiting messages after it (scores) |
|---|---|---|
| 12 | the root | 12 |
| 5 | left reply of 12 | 12, 5 |
| 8 | left reply of 5 | 12, 5, 8 |
| # | no left reply of 8 | 12, 5, 8 |
| # | no right reply of 8 | 12, 5 |
| # | no right reply of 5 | 12 |
| -4 | right reply of 12 | 12, -4 |
| # | no left reply of -4 | 12, -4 |
| 3 | right reply of -4 | 12, -4, 3 |
| # | no left reply of 3 | 12, -4, 3 |
| # | no right reply of 3 | none |
Input: values = [7], left = [-1], right = [-1]
Output: ["7,#,#", "7"]One message has two missing replies. The loaded text drops the marks at the end.
Input: values = [], left = [], right = []
Output: ["#", ""]An empty thread is one missing root, so the saved text is a single mark.
0 ≤ length of values ≤ 2 × 10^5values, left and right have the same length.-10^9 ≤ values[i] ≤ 10^9, and scores may repeat.left and right form a binary tree rooted at message 0.A tree of 200,000 messages is saved as 400,001 tokens: one for each message and one for each missing reply. The text has about 2.8 million characters at most, so it must be built once, with a list of pieces or a string builder.
The tree can be 200,000 levels deep. A function that calls itself for each subtree raises a RecursionError in Python after about 1,000 levels, and risks a stack overflow in Java and C++.