Press enter to see results or esc to cancel.

Binary Tree Inorder Traversal Leetcode Problem 94 [Python Solution]

Welcome, beginners!

Today, we're going to tackle the Binary Tree Inorder Traversal problem on LeetCode.

This is a great opportunity to explore both recursive and iterative solutions, shedding light on the inner workings of tree traversal.

So, let's dive in!

Problem Overview

The problem statement on LeetCode is quite straightforward.

Given the root of a binary tree, your task is to return the inorder traversal of its nodes' values.

In simpler terms, you need to visit all the nodes in a specific order and collect their values.

But before we delve into the solutions, let's understand the problem better by considering an example:

Example 1:

Suppose we have a binary tree with the following structure:

    1
     
      2
     /
    3

In this case, the inorder traversal should yield [1, 3, 2].

This order represents visiting the nodes in the left subtree, then the current node, and finally the right subtree.

Understanding Binary Tree Inorder Traversal Constraints

Before we proceed to the solutions, let's take a moment to understand the constraints set for this problem:

  • The number of nodes in the tree falls within the range of [0, 100].
  • The values of nodes (Node.val) are integers in the range [-100, 100].

Binary Tree Inorder Traversal – LeetCode Python Solution

Now, let's explore two approaches to solving this problem: a recursive solution and an iterative solution.

Both approaches follow the same basic principles of inorder traversal.

1. Recursive Approach

The recursive approach is the most intuitive way to perform an inorder traversal.

We'll use a recursive function to traverse the tree while adding nodes to the result in the desired order.

def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
    # Initialize an empty list to store the result.

res = []

    # Define a recursive helper function for the traversal.

def helper(node):
        if not node:
            return
        # Recursively traverse the left subtree.

helper(node.left)
        # Add the current node's value to the result.

res.append(node.val)
        # Recursively traverse the right subtree.

helper(node.right)

    # Start the traversal from the root node.

helper(root)
    return res

Time Complexity: In the worst case, the time complexity of this recursive solution is O(n) because we must visit every node in the tree.

Space Complexity: The memory complexity in the worst case is also O(n) due to the function call stack.

2. Iterative Approach

The iterative approach simulates the function call stack using a stack data structure.

This method allows us to achieve the same result without the overhead of recursive function calls.

def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
    # Initialize an empty list to store the result.

res = []
    # Initialize an empty stack.

stack = []
    cur = root

    while cur or stack:
        while cur:
            # Traverse left and push nodes onto the stack.

stack.append(cur)
            cur = cur.left
        # Pop a node from the stack.

cur = stack.pop()
        # Add the current node's value to the result.

res.append(cur.val)
        # Move to the right subtree.

cur = cur.right

    return res

In this iterative approach, we use a stack to simulate the recursive function calls.

We push nodes onto the stack as we traverse the left subtree and pop them when we visit nodes during the backtracking phase.

Time Complexity: The time complexity remains O(n) because we must visit every node in the tree.

Space Complexity: The space complexity is also O(n) in the worst case due to the stack used for simulation.

Reasoning Behind Our Approach

Both the recursive and iterative approaches share the same underlying logic of inorder traversal.

They first explore the left subtree, then visit the current node, and finally traverse the right subtree.

The key difference lies in how they handle the function call stack.

The recursive approach relies on the implicit function call stack, which keeps track of the function calls for each node.

In contrast, the iterative approach uses an explicit stack to simulate the same behavior.

Related Interview Questions By Company:

Related Interview Questions By Difficulty:

Conclusion

In this beginner-friendly guide, we tackled the Binary Tree Inorder Traversal problem on LeetCode.

We explored both recursive and iterative solutions, gaining a deeper understanding of tree traversal.

If you found this guide helpful, please consider liking and subscribing to support our our platform.

You can also check out our Patreon for additional ways to support us.

Remember that practice makes perfect, so keep coding and stay curious!

Now you have two Python solutions at your disposal for Binary Tree Inorder Traversal, ready to tackle similar tree traversal problems on LeetCode and beyond.

Question Link

Please feel free to comment, ask questions, make suggestions, and share this content with fellow learners.

Happy coding!

>