Tutorialspoint
Problem
Solution
Submissions

Binary Tree Traversals

Certification: Advanced Level Accuracy: 33.33% Submissions: 6 Points: 15

ite a Python function that performs inorder, preorder, and postorder traversal of a binary tree. Each traversal should return a list of node values in the order they are visited.

Example 1
  • Input:
    [1,null,2,3]
    Tree:

    Binary Tree Traversals with maximum value 3


  • Output:
    Inorder: [1, 3, 2]
    Preorder: [1, 2, 3]
    Postorder: [3, 2, 1]
Example 2
  • Input:
    [1,2,3,4,5]
    Tree:

    Binary Tree Traversals with maximum value 5

  • Output:
    Inorder: [4, 2, 5, 1, 3]
    Preorder: [1, 2, 4, 5, 3]
    Postorder: [4, 5, 2, 3, 1]
Constraints
  • 0 ≤ nodes ≤ 100
  • -100 ≤ Node.val ≤ 100
  • Time Complexity: O(n)
  • Space Complexity: O(h)
RecursionGoogleTutorialspoint
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 recursive approach for simplicity
  • Inorder: left subtree, current node, right subtree
  • Preorder: current node, left subtree, right subtree
  • Postorder: left subtree, right subtree, current node
  • Can be implemented iteratively using a stack for O(1) space complexity

Steps to solve by this approach:

 Step 1: Implement inorder traversal (Left, Root, Right) using recursion.

 Step 2: Implement preorder traversal (Root, Left, Right) using recursion.
 Step 3: Implement postorder traversal (Left, Right, Root) using recursion.
 Step 4: For each traversal, visit left subtree, right subtree, and root in the appropriate order.
 Step 5: Collect visit results into separate lists for each traversal type.
 Step 6: Return all three traversal results.

Submitted Code :