1

Currently I'm representing a binary tree in the following manner:

[None,2,[None,3,None]]

The tree above is rooted at 2. None means that the branch is empty.

I'd rather implement this in a list. Are there better ways to do this (without resorting to creating classes) ?

3
  • 10
    Why the aribtrary limitation "without resorting to creating classes"? I think the best way to do this is to define a class. Commented May 31, 2011 at 11:53
  • "Better ways" in which respect? More efficient? Commented May 31, 2011 at 12:16
  • Consider using a single flat list: stackoverflow.com/a/79560414/2429666 Commented Apr 7 at 20:18

3 Answers 3

4

If you want to represent a complete binary tree (i.e. with all nodes having two children, except the leaves), then you can use just a flat list the represent the tree.

You can easily determine the father and two children of a node like this:

def leftChild(lst,i):
  try: 
    return lst[i*2]
  except IndexError:
    return None

def rightChild(lst,i):
  try: 
    return lst[i*2+1]
  except IndexError:
    return None

def father(lst,i):
  try:
    return lst[i/2]
  except IndexError:
    return None
Sign up to request clarification or add additional context in comments.

Comments

3

It is possible to represent a binary tree using a flat list, as described here. How wasteful this method is would depend on the shape of your tree.

I am curious as to why you insist on avoiding classes. If you were to wrap this in a class, you could define a clean API and hide the details of your implementation from the eventual user.

Comments

0

Here is my way: an array of arrays, where item with index 0 is a root item:

[['Level A', 'A1', 'A2'], ['Level B', 'B1', 'B2'], ['Level C', 'C1', 'C2']]

Classes can make a simple application unnecessarily complex, especially if you deal with simple trees like represented above.

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.