Ejemplo n.º 1
0
 def helper(pre_order, cur_idx=0, min=float('-inf'), max=float('inf')):
     if cur_idx >= len(pre_order):
         return None, 0
     cur_node = BinaryNode(pre_order[cur_idx])
     cur_idx += 1
     if cur_idx < len(pre_order) and min <= pre_order[cur_idx] <= cur_node.data:
         cur_node.left, cur_idx = helper(pre_order, cur_idx, min, cur_node.data)
     if cur_idx < len(pre_order) and cur_node.data < pre_order[cur_idx] <= max:
         cur_node.right, cur_idx = helper(pre_order, cur_idx, cur_node.data, max)
     return cur_node, cur_idx
Ejemplo n.º 2
0
    def make_tree(pre_remaining, in_map, in_start=0, in_end=None):  # End index exclusive
        if not in_end:
            in_end = len(pre_remaining)

        if not pre_remaining or in_map[pre_remaining[0]] >= in_end or in_start >= in_end:
            return None

        cur_node = BinaryNode(pre_remaining.popleft())
        left_end = in_map[cur_node.data] + 1

        cur_node.left = make_tree(pre_remaining, in_start, left_end)
        cur_node.right = make_tree(pre_remaining, left_end, in_end)

        return cur_node
            else:
                cur_node = cur_node.right
        last_node = old_cur

    return out


def get_first_in_order_node(b_tree):
    first = b_tree
    while first and first.left:
        first = first.left
    return first


b = BinaryNode(1)
c = BinaryNode(3)
a = BinaryNode(2, b, c)

assert in_order(a) == [1, 2, 3]

f = BinaryNode(5)
g = BinaryNode(7)
e = BinaryNode(6, f, g)
d = BinaryNode(4, right=e)
c.right = d

assert in_order(a) == [1, 2, 3, 4, 5, 6, 7]

h = BinaryNode(4)
assert in_order(h) == [4]