0

I have a list of numbers like [1, 2, 2, 3, 3, 2, 3, 3, 4] which I need to convert into a tree, like below:

             1
          /  |  \
         2   2   2
            / \  / \
           3   3 3  3
                    \
                     4

Note: within the list, each number cannot be +2 or more than +2 compared to the preceding value.

1
  • Hi Ajay, welcome to StackOverflow. Could you include code that you have tried so far? Commented Dec 17, 2019 at 18:10

1 Answer 1

1

This can be done in a natural way, using a stack of nodes:

  • Initialise an empty stack.
  • For each number x in the list:
    • Create a node node with value x.
    • Pop until either the stack is empty, or the top node in the stack has value x - 1.
    • If the stack is non-empty, add an edge from node to the node at the top of the stack.
    • Push node to the stack.
  • Return the node at the bottom of the stack; this is the root node.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.