Solving Leetcode Interviews in Seconds with AI: Binary Tree Preorder Traversal
Introduction
In this blog post, we will explore how to solve the LeetCode problem "144" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
Given the root of a binary tree, return the preorder traversal of its nodes' values. Example 1: Input: root = [1,null,2,3] Output: [1,2,3] Explanation: Example 2: Input: root = [1,2,3,4,5,null,8,null,null,6,7,9] Output: [1,2,4,5,6,7,3,8,9] Explanation: Example 3: Input: root = [] Output: [] Example 4: Input: root = [1] Output: [1] Constraints: The number of nodes in the tree is in the range [0, 100]. -100 <= Node.val <= 100 Follow up: Recursive solution is trivial, could you do it iteratively?
Explanation
- Iterative Approach: Use a stack to simulate the recursive calls. Start by pushing the root onto the stack. While the stack is not empty, pop a node, add its value to the result, and then push its right and left children onto the stack (right child first to ensure left is processed before right).
- Handling Null Nodes: Carefully handle null nodes by not pushing them onto the stack. This avoids unnecessary processing and potential errors.
- Order of Processing: By pushing the right child before the left, the left child is processed first after the current node, maintaining the preorder traversal order (Node, Left, Right).
- Runtime Complexity: O(N), where N is the number of nodes in the tree.
- Storage Complexity: O(N) in the worst-case scenario (skewed tree). In a balanced tree, the space complexity will be O(log N).
Code
from typing import List, Optional
# 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]:
if not root:
return []
result = []
stack = [root]
while stack:
node = stack.pop()
result.append(node.val)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return result