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?
HAPPY CASE
Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]
Input: root = [2,1,3]
Output: [2,3,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: Recursively swap left node for right node.
1. Basecase is a Null Node
2. Swap the left and right nodes
3. Return the node with swapped children.
⚠️ 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 invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
# Basecase is a Null Node
if not root:
return None
# Swap the left and right nodes
root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
# Return the node with swapped children
return root
class Solution {
public TreeNode invertTree(TreeNode root) {
// Basecase is a Null Node
if(root == null){
return root;
}
// Swap the left and right nodes
invertTree(root.left);
invertTree(root.right);
TreeNode curr = root.left;
root.left = root.right;
root.right = curr;
// Return the node with swapped children
return root;
}
}
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 binary tree
O(N)
, because we need to visit each node in the binary treeO(N)
because we need to account for unbalanced tree (space is used for the recursion stack). In the general case O(logN)
for balanced tree.