class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
def printPaths(root): 
    path = []
    printPathsRec(root, path, 0)
def printPathsRec(root, path, pathLen):  
    if root is None:
        return
    if(len(path) > pathLen):
        path[pathLen] = root.data
    else:
        path.append(root.data)
    pathLen = pathLen + 1
    if root.left is None and root.right is None:
        printArray(path, pathLen)
    else:
    
        printPathsRec(root.left, path, pathLen)
        printPathsRec(root.right, path, pathLen)

def printArray(ints, len):
    for i in ints[0 : len]:
        print(i," ",end="")
    print()
 

from binarytree import build

values = [7, 3, 2, 6, 9, None, 1, 5, 8]
root = build(values)
print(root) 
printPaths(root.value)
.

I need to build binary tree with build and make the code work, but i can't find out the way. This example is get from internet,they use method like

root = Node(10)
root.left = Node(8)
root.right = Node(2)
root.left.left = Node(3)
root.left.right = Node(5)
root.right.left = Node(2)
printPaths(root)

But i need to use another method to make it happen.


Solution 1:

I am going to guess that values contains the level-order values of the tree, where the children below a None are not included (instead of having two filler None values).

Then the algorithm to populate a new tree will also follow a level-order way of populating. For this you typically use a queue or deque or two lists. For example:

def build(values):
    if not values:
        return
    it = iter(values)
    root = Node(next(it))
    level = [root]
    while level:
        nextlevel = []
        for parent in level:
            value = next(it, None)
            if value is not None:
                parent.left = Node(value)
                nextlevel.append(parent.left)
            value = next(it, None)
            if value is not None:
                parent.right = Node(value)
                nextlevel.append(parent.right)
        level = nextlevel
    return root