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.
Devkinandan Chauhan
1,9333 gold badges22 silver badges53 bronze badges
-
Edit the question to show what you have tried.Michael Butscher– Michael Butscher2020年03月07日 15:53:26 +00:00Commented Mar 7, 2020 at 15:53
-
1It depends on your purpose and use case.Boseong Choi– Boseong Choi2020年03月07日 15:58:54 +00:00Commented Mar 7, 2020 at 15:58
1 Answer 1
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
flashton
I particularly appreciate the repr method example. Thanks!
Runeaway3
@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/…
Explore related questions
See similar questions with these tags.
lang-py