Given a Binary Search Tree, for example:
9
8
7
5
3
2
I would like to get an in-order list of nodes with values between a and b (inclusive).
I have implemented a recursive helper function:
def _range(root, a, b):
node_list = []
if root.left:
node_list.append(_range(root.left, a, b))
if root.value >= a and root.value <= b:
node_list.append(root)
if root.right:
node_list.append(_range(root.right, a, b))
return node_list
Which gives me:
[[[BTNode: 2], BTNode: 3], BTNode: 5, [BTNode: 7, [[BTNode: 8], BTNode: 9]]]
I however need:
[BTNode: 2, BTNode: 3, BTNode: 5, BTNode: 7, BTNode: 8, BTNode: 9]
Is there anyway to flatten the list? I realize that what I am doing is appending a list to another list, but am not sure how to fix this without breaking the code.
node_list.extend
instead ofnode_list.append
? An other solution would be to pass the list as parameter. – Bakuriu Nov 6 '12 at 17:56