1

Need help to understand what's going with following code.


def in_order(root : TreeNode, res = []):
    if root:
        in_order(root.left, res)
        res.append(root.key)
        in_order(root.right, res)
    return res


tree = create_tree([12,5,18,2,9,15,19,17])
print(in_order(tree.root))
delete(tree, 5)
print(in_order(tree.root))

Same list is used and output is

[2, 5, 9, 12, 15, 18, 19]
[2, 5, 9, 12, 15, 18, 19, 2, 9, 12, 15, 18, 19]

Following code produces correct output

def in_order(root : TreeNode, res):
    if root:
        in_order(root.left, res)
        res.append(root.key)
        in_order(root.right, res)
    return res

tree = create_tree([12,5,18,2,9,15,19,17])
print(in_order(tree.root, []))
delete(tree, 5)
print(in_order(tree.root, []))

Output

[2, 5, 9, 12, 15, 18, 19]
[2, 9, 12, 15, 18, 19]
Vatsal
  • 11
  • 3

0 Answers0