Write the function to return Binary Search Tree in sorted order. class BinarySea
ID: 3919816 • Letter: W
Question
Write the function to return Binary Search Tree in sorted order.
class BinarySearchTree:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
# this is function, not a method
def items(tree):
"""
Return the items in tree in sorted order
without using sort or sorted
"""
Example:
print(get_sorted_order(BinarySearchTree(4, BinarySearchTree(2),
BinarySearchTree(6,
BinarySearchTree(5))))
>>> [2, 4, 5, 6]
Explanation / Answer
class BinarySearchTree: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right # this is function, not a method def items(tree): """ Return the items in tree in sorted order without using sort or sorted """ current = tree s = [] result = [] while True: if current is not None: s.append(current) current = current.left else: if len(s) > 0: current = s.pop() result.append(current.value) current = current.right else: return result print(items(BinarySearchTree(4, BinarySearchTree(2), BinarySearchTree(6, BinarySearchTree(5)))))
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.