Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Binary Tree Inorder Traversal

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "94" 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 inorder traversal of its nodes' values. Example 1: Input: root = [1,null,2,3] Output: [1,3,2] Explanation: Example 2: Input: root = [1,2,3,4,5,null,8,null,null,6,7,9] Output: [4,2,6,5,7,1,3,9,8] 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

Here's the breakdown of the approach, complexity, and the Python code for an iterative inorder traversal of a binary tree.

  • Key Approach:

    • Use a stack to simulate the recursive calls.
    • Iteratively go left until a null node is encountered, pushing nodes onto the stack.
    • Pop nodes from the stack, add their value to the result, and then move to the right child.
  • Complexity:

    • Runtime: O(N), where N is the number of nodes in the tree.
    • Storage: O(H), where H is the height of the tree (worst case O(N) for skewed tree, average case O(log N) for balanced tree).

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 inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        result = []
        stack = []
        curr = root

        while curr or stack:
            while curr:
                stack.append(curr)
                curr = curr.left

            curr = stack.pop()
            result.append(curr.val)
            curr = curr.right

        return result

More from this blog

C

Chatmagic blog

2894 posts