Community

Start a Thread


Notifications
Subscribe You’re not receiving notifications from this thread.

String From Binary Tree (Main Thread)

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).

Constraints

  • The number of nodes in the binary tree would be <= 100000
  • The nodes will always contain integer values between -1000000000 and 1000000000
  • Expected time complexity : O(n)
  • Expected space complexity : O(logn)

You can see the full challenge with visuals at this link.

Challenges • Asked over 6 years ago by Jake from AlgoDaily

Jake from AlgoDaily Commented on Nov 30, 2017:

This is the main discussion thread generated for String From Binary Tree.