This is a really basic problem to make sure you know how to implement a preorder traversal - you won't get something this easy in an interview.
Problem: Given the root
node of a binary tree, return the preorder traversal of its nodes.
Example:
Hint: Remember, the preorder traversal first does something on a node "pre" doing it on its children.
We want to do a preorder traversal over all the nodes in the tree.
1. Recursion
The recursion for a preorder traversal is to visit the current node, then all the nodes to the left, then right, c L R
.
When we visit each node, we add its value to an array. Here's the recursion:
2. Base case
This recursion will keep calling itself on deeper and deeper nodes in the tree. Eventually, it calls itself on a null node, preorder(null)
. In this case, we don't want to traverse any further and we should just do nothing.
3. Code
To code the preorder traversal function, we just combine the recursion and base case. After calling this function, we return the values
array that it filled in.
Time Complexity O(n). We walk through all of the nodes in the tree, which is n nodes total.
Space Complexity O(n). The recursive function calls are stored inside of the Call Stack, which grows up to the depth of the tree. The tree might be a flat line, in which case it's n nodes deep.
TreeNode.of
function can be used to create an entire binary tree using 1 line of code. The input is a BFS traversal of the tree including nulls, and the output is the root node of the tree.TreeNode.of([1, None, 2, None, 3])
ListNode.of
function lets you create an entire Linked List using 1 line of code. The input is an array, and the output is the head of the Linked List.ListNode.of([1, 2, 3])
ListNode.of([1, 2, 3], 1)
GraphNode.of
function lets you create an entire Graph using 1 line of code. The input is an Adjacency Matrix, and the output is the first node in the matrix.GraphNode.of([ ['A', 1, 2], ['B', 2], ['C', 0] ])
[['__init__', 15], ['add', 16], ['get']]
c = MyClass(15) c.add(16) c.get()
TreeNode.of
function can be used to create an entire binary tree using 1 line of code. The input is a BFS traversal of the tree including nulls, and the output is the root node of the tree.TreeNode.of([1, None, 2, None, 3])
ListNode.of
function lets you create an entire Linked List using 1 line of code. The input is an array, and the output is the head of the Linked List.ListNode.of([1, 2, 3])
ListNode.of([1, 2, 3], 1)
GraphNode.of
function lets you create an entire Graph using 1 line of code. The input is an Adjacency Matrix, and the output is the first node in the matrix.GraphNode.of([ ['A', 1, 2], ['B', 2], ['C', 0] ])
[['__init__', 15], ['add', 16], ['get']]
c = MyClass(15) c.add(16) c.get()