2

Given a list of nodes and the number of children it has, construct a (non-binary) tree from this list (which is in pre-order traversal)

for example I am given the following:

1 3
2 1
3 0
4 0
5 0

which is a tree that looks like

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

I know I should use recursion to construct this tree, but because it's not a binary tree, I'm pretty lost as to how this algorithm should be implemented.

1
  • Welcome to stackoverflow. Why don't you give it a try first. And when you get stuck, come back to the site and ask specific questions about your code. Commented Oct 9, 2015 at 20:09

1 Answer 1

3

Before feeding you the code to solve your problem I'd like to play a thought game with you. Take a look at the following image which represents how recursions should unroll for your input

enter image description here

Study the image and notice how recursions are only started when there are children for a specific node (and that they last for the number of children indicated in the input).

Try to come up with a code (or a pseudocode) on paper.


The code to solve this it is pretty straightforward: use a vector<Node> to store your children

#include <iostream>
#include <vector>
using namespace std;

struct Node {
  Node(int v) : val(v) {}
  int val;
  vector<Node*> children;
};

Node *readTreeNode() {
  int val, children;
  cin >> val >> children;
  Node *node = new Node(val);
  for (int i = 0; i<children; ++i)
    node->children.push_back(readTreeNode());
  return node;
}

int main() {
  Node *root = readTreeNode();
  // Do the cleanup..
  return 0;
}

Live Example

Notice the loop where the readTreeNode() function is recursively called

for (int i = 0; i<children; ++i)
    node->children.push_back(readTreeNode());

inner children are processed before the others.

Final caveats:

  1. I didn't implement memory handling (the code above leaks memory). Be a good citizen and free your allocated memory or, even better, use smart pointers.

  2. There's no error handling (i.e. no check for input nodes effectively being entered)

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.