Understand what the interviewer is asking for by using test cases and questions about the problem.
- Established a set (2-3) of test cases to verify their own solution later.
- Established a set (1-2) of edge cases to verify their solution handles complexities.
- Have fully understood the problem and have no clarifying questions.
- Have you verified any Time/Space Constraints for this problem?
N
represents the number of nodes in Tree. O(N)
time complexity and O(N)
space complexityHAPPY CASE
Input: root = [1,null,2,3]
Output: [1,2,3]
Input: root = [1]
Output: [1]
EDGE CASE
Input: root = []
Output: []
Match what this problem looks like to known categories of problems, e.g. Linked List or Dynamic Programming, and strategies or patterns in those categories.
If you are dealing with Binary Trees some common techniques you can employ to help you solve the problem:
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Pre-Order traverse is process-left-right. Lets store, go left, and go right for each node.
1. Create a helper function to recursively progress through the nodes.
a. Basecase, root is none.
b. Store node value into results
c. Go to left node
d. Go to right node
2. Create results array
3. Call helper function to build results
4. Return results
⚠️ Common Mistakes
Implement the code to solve the algorithm.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
# Create a helper function to recursively progress through the nodes.
def helper(root:Optional[TreeNode]):
# Basecase, root is none.
if not root:
return
# Store node value into results
result.append(root.val)
# Go to left node
helper(root.left)
# Go to right node
helper(root.right)
# Create results array
result = []
# Call helper function to build results
helper(root)
# Return results
return result
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
// Create results array
List<Integer> pre = new LinkedList<Integer>();
// Call helper function to build results
preHelper(root,pre);
// Return results
return pre;
}
// Create a helper function to recursively progress through the nodes
public void preHelper(TreeNode root, List<Integer> pre) {
// Basecase, root is none
if(root==null) return;
// Store node value into results
pre.add(root.val);
// Go to left node
preHelper(root.left,pre);
// Go to right node
preHelper(root.right,pre);
}
}
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
Evaluate the performance of your algorithm and state any strong/weak or future potential work.
Assume N
represents the number of nodes in Tree
O(N)
because we need to visit each node in binary tree.O(N)
because we need to create a results array with the values from all the nodes.