Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug in build and levelorder function #27

Closed
fuyb1992 opened this issue Sep 10, 2020 · 3 comments
Closed

Bug in build and levelorder function #27

fuyb1992 opened this issue Sep 10, 2020 · 3 comments

Comments

@fuyb1992
Copy link

Tree:

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

Code:

from binarytree import build
li = [5, 2, 3, None, None, 2, 4, 3, 1]
build(li)

Error:

File "C:\Program Files\Python37\lib\site-packages\binarytree\__init__.py", line 1811, in build
    'parent node missing at index {}'.format(parent_index))

FYI:

def build(values):
    ...
    nodes = [None if x is None else Node(x) for x in data]
    non_null_nodes = [x for x in nodes if x is not None]
    for i in range(1, len(nodes)):
        if nodes[i] is not None:
            parent_index = (i - 1) // 2
            parent = non_null_nodes[parent_index]
    ...
def levelorder(self):
    ...
    current_level = [self]
    res = []
    while current_level:
        next_level = []
        for node in current_level:
            if node:
                res.append(node.val)
                next_level.append(node.left)
                next_level.append(node.right)
            else:
                res.append(None)
        current_level = next_level
    while res:
        if res[-1] is None:
            res.pop()
        else:
            break
    return res
@joowani
Copy link
Owner

joowani commented Sep 10, 2020

Hi @fuyb1992,

It should be [5,2,3,None,None,2,4,None,None,None,None,3,1].

@fuyb1992
Copy link
Author

Hi @joowani
[5,2,3,None,None,2,4,None,None,None,None,3,1] works, but it is confused that None node has child node.

@joowani
Copy link
Owner

joowani commented Sep 11, 2020

Hi @fuyb1992,

it may seem unintuitive at first, but that's just how binary trees are represented in arrays. If there is a more succinct way, please let me know and I will consider adding it to the library. Thanks.

@joowani joowani closed this as completed Oct 6, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants