2

example

Does anyone have an idea as to how I could recreate this:

The end objective is to traverse the tree and count every endpoint. In this case 3 because 1, 3, 2 are all endpoints.

2
  • Edit the question to show what you have tried. Commented Mar 7, 2020 at 15:53
  • 1
    It depends on your purpose and use case. Commented Mar 7, 2020 at 15:58

1 Answer 1

2

If you don't want to use simple lists, you could build a basic class. Something like:

class NonBinTree:

    def __init__(self, val):
        self.val = val
        self.nodes = []

    def add_node(self, val):
        self.nodes.append(NonBinTree(val))

    def __repr__(self):
        return f"NonBinTree({self.val}): {self.nodes}"


a = NonBinTree(0)
a.add_node(1)
a.add_node(3)
a.add_node(4)
a.nodes[2].add_node(2)

print(a)

And then add whatever other methods you want.

Sign up to request clarification or add additional context in comments.

2 Comments

I particularly appreciate the repr method example. Thanks!
@chuck If I have the same set up, but instead had the nodes structured as variables & coefficients, how would I be able to define the nodes via their baseline children components? As I ask in this question:stackoverflow.com/questions/73903349/…

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.