← Back to Binary Trees

Collect All Values

2 of 7

Exercise: Collect All Values

Your Task

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.


Examples

# 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)) # []

Approach

This is almost identical to the inorder example from the intro — just change the order:

  • Preorder: [root.val] + left values + right values
  1. Base case: if root is None, return an empty list []
  2. Collect all values from the left subtree
  3. Collect all values from the right subtree
  4. Return [root.val] + left_values + right_values

Hints

Try it yourself

Code: Collect All Values

Loading Python runtime…
Python …
Loading...
bash
$ Click "Run" to execute your code...