joowani / binarytree

Python Library for Studying Binary Trees
http://binarytree.readthedocs.io
MIT License
1.81k stars 171 forks source link

Error when building tree from list #17

Closed jeffreywu1996 closed 6 years ago

jeffreywu1996 commented 6 years ago

Hi, I was looking at documentation for building a tree from list. Below is from the documentation,

>>> from binarytree import build
>>>
>>> # Build a tree from list representation
>>> root = build([7, 3, 2, 6, 9, None, 1, 5, 8])
>>> print(root)
#
#            __7
#           /   \
#        __3     2
#       /   \     \
#      6     9     1
#     / \
#    5   8
#

Then I tried

>>> root = build([7, 3, 2, 6, 9, None, 1, 5, 8, 1, 2])
>>> print(root)

        ______7
       /       \
    __3__       2
   /     \       \
  6       9       1
 / \     / \
5   8   1   2

But when I tried to add one more leaf to the node, I get an error.

>>> root = build([7, 3, 2, 6, 9, None, 1, 5, 8, 1, 2, 3])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/binarytree/__init__.py", line 1651, in build
    .format(parent_index)
binarytree.exceptions.NodeNotFoundError: Parent node missing at index 5

It seems I cannot add the 3 to tree because theres a None node at index 5. I think the 3 should instead be added to the left child node of 1 (index 6)

joowani commented 6 years ago

Hi @jeffreywu1996,

Well no because you would be violating the rules of list representation.

Left child of Node(1) at index 6 would have index 13 (not 11, which is where you are trying to place the 3). So you would need to do this instead:

In [1]: print(build([7, 3, 2, 6, 9, None, 1, 5, 8, 1, 2, None, None, 3]))
# 
#         ______7
#        /       \
#     __3__       2__
#    /     \         \
#   6       9         1
#  / \     / \       /
# 5   8   1   2     3
jeffreywu1996 commented 6 years ago

Thanks for the explanation!

joowani commented 6 years ago

No problem!