94. Binary Tree Inorder Traversal LeetCode Solution

In this guide, you will get 94. Binary Tree Inorder Traversal LeetCode Solution with the best time and space complexity. The solution to Binary Tree Inorder Traversal problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Binary Tree Inorder Traversal solution in C++
  4. Binary Tree Inorder Traversal solution in Java
  5. Binary Tree Inorder Traversal solution in Python
  6. Additional Resources
94. Binary Tree Inorder Traversal LeetCode Solution image

Problem Statement of Binary Tree Inorder Traversal

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?

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(n)

94. Binary Tree Inorder Traversal LeetCode Solution in C++

class Solution {
 public:
  vector<int> inorderTraversal(TreeNode* root) {
    vector<int> ans;
    stack<TreeNode*> stack;

    while (root != nullptr || !stack.empty()) {
      while (root != nullptr) {
        stack.push(root);
        root = root->left;
      }
      root = stack.top(), stack.pop();
      ans.push_back(root->val);
      root = root->right;
    }

    return ans;
  }
};
/* code provided by PROGIEZ */

94. Binary Tree Inorder Traversal LeetCode Solution in Java

class Solution {
  public List<Integer> inorderTraversal(TreeNode root) {
    List<Integer> ans = new ArrayList<>();
    Deque<TreeNode> stack = new ArrayDeque<>();

    while (root != null || !stack.isEmpty()) {
      while (root != null) {
        stack.push(root);
        root = root.left;
      }
      root = stack.pop();
      ans.add(root.val);
      root = root.right;
    }

    return ans;
  }
}
// code provided by PROGIEZ

94. Binary Tree Inorder Traversal LeetCode Solution in Python

class Solution:
  def inorderTraversal(self, root: TreeNode | None) -> list[int]:
    ans = []
    stack = []

    while root or stack:
      while root:
        stack.append(root)
        root = root.left
      root = stack.pop()
      ans.append(root.val)
      root = root.right

    return ans
# code by PROGIEZ

Additional Resources

See also  125. Valid Palindrome LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.