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_values