Tutorialspoint
Problem
Solution
Submissions

Binary Tree Inorder Traversal

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 10

Write a C# program to perform an inorder traversal of a binary tree iteratively (without recursion). Inorder traversal visits the left subtree, then the root node, and finally the right subtree. Return the values of the nodes in the order they are visited.

Example 1
  • Input: root = [1,null,2,3]

    Binary Tree Inorder Traversal with right and left subtree

  • Output: [1,3,2]
  • Explanation:
    • Inorder traversal first visits the left subtree (none for node 1).
    • Then visits the root (1).
    • Then visits the right subtree (2 and 3), where it first visits the left child of 2 (which is 3).
    • Finally, it visits node 2.
    • The result is [1,3,2].
Example 2
  • Input: root = []
  • Output: []
  • Explanation:
    • The tree is empty, so the result is an empty list.
Constraints
  • The number of nodes in the tree is in the range [0, 100]
  • -100 <= Node.val <= 100
  • Time Complexity: O(n) where n is the number of nodes
  • Space Complexity: O(h) where h is the height of the tree
Binary TreeStackMicrosoftWalmart
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a stack to simulate the recursive call stack
  • Push nodes onto the stack as you traverse down the left subtree
  • When you can't go left anymore, pop a node, process it, and go to its right subtree
  • Repeat until the stack is empty and all nodes are processed
  • Remember to avoid revisiting nodes by properly managing the current node pointer

Steps to solve by this approach:

 Step 1: Initialize an empty result list and a stack to simulate the recursive call stack.
 Step 2: Set the current node pointer to the root of the tree.
 Step 3: While the current node is not null or the stack is not empty:
 Step 4: If the current node is not null, push it onto the stack and move to its left child.
 Step 5: If the current node is null, pop a node from the stack, add its value to the result list, and move to its right child.
 Step 6: Continue this process until all nodes are processed (current is null and stack is empty).
 Step 7: Return the result list containing the inorder traversal.

Submitted Code :