2 of 7
Write a function get_values(root) that returns a list of all node values in the tree, visited in preorder order: root first, then left subtree, then right subtree.
# 1 # / \ # 2 3 # / \ # 4 5 root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) root.left.left = TreeNode(4) root.left.right = TreeNode(5) print(get_values(root)) # [1, 2, 4, 5, 3]
# 7 # \ # 9 root = TreeNode(7) root.right = TreeNode(9) print(get_values(root)) # [7, 9]
print(get_values(None)) # []
This is almost identical to the inorder example from the intro β just change the order:
[root.val] + left values + right valuesroot is None, return an empty list [][root.val] + left_values + right_valuesWhat do you return when the tree is empty? There are no values to collect, so return an empty list.
if root is None: return []
After collecting the left and right values recursively, put them together with the current node's value first.
left_vals = get_values(root.left) right_vals = get_values(root.right) return [root.val] + left_vals + right_vals
def get_values(root): if root is None: return [] left_vals = get_values(root.left) right_vals = get_values(root.right) return [root.val] + left_vals + right_vals
Why this works: Each node returns a list starting with itself, followed by everything in its left subtree, then everything in its right subtree. Leaf nodes return [leaf.val] + [] + [] = [leaf.val]. These lists get joined as the recursion unwinds.