Here is the interview question prompt, presented for reference.
Suppose we're given a simple binary tree
like the following:
1
/ \
2 3
\
4
Can you generate a string based off the values of its nodes?
With this string, we're going to want to capture the number/key at each node, as well as model the relationships between nodes. The order the nodes appear in the string would be based on the tree's pre-order traversal.
Let's look at an example of this peculiar format. In the tree above, we have nodes 1
, 2
, 3
, and 4
. We'll use brackets to represent the child nodes of a node.
Note that in our tree, 2
and 3
are children of 1
. The relationship can be represented like:
1[[2][3]]
To expand on the string, the child of 3
would be added in this manner:
1[[2][3[[4]]]]
Note the use of double brackets. Each child node aside from the root should be wrapped in its own set of brackets.
Where there are no nodes present (e.g. 3
has no left child node), we can simply skip that iteration. The method will be called via stringFromTree(tree)
.
100000
-1000000000
and 1000000000
O(n)
O(logn)
You can see the full challenge with visuals at this link.
Challenges • Asked almost 7 years ago by Jake from AlgoDaily
This is the main discussion thread generated for String From Binary Tree.