Tutorialspoint
Problem
Solution
Submissions

Binary Tree Traversals

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

Write a JavaScript program to perform three different traversals of a binary tree: In-order (left, root, right), Pre-order (root, left, right), and Post-order (left, right, root). Each traversal visits all nodes in the tree but in different orders.

Example 1
  • Input: root = [1,null,2,3]
  • Output: - Inorder: [1,3,2] - Preorder: [1,2,3] - Postorder: [3,2,1]
  • Explanation:
    • The tree has root 1, right child 2, and 2 has left child 3.
    • Inorder traversal visits left subtree, root, then right subtree.
    • Preorder traversal visits root, then left subtree, then right subtree.
    • Postorder traversal visits left subtree, right subtree, then root.
Example 2
  • Input: root = [1,2,3,4,5,6,7]
  • Output: - Inorder: [4,2,5,1,6,3,7] - Preorder: [1,2,4,5,3,6,7] - Postorder: [4,5,2,6,7,3,1]
  • Explanation:
    • This is a complete binary tree with 7 nodes.
    • Each traversal follows its specific order pattern.
    • Inorder gives sorted order for BST, but this is not necessarily a BST.
    • Preorder processes root first, postorder processes root last.
Constraints
  • The number of nodes in the tree is in the range [0, 100]
  • -100 ≤ Node.val ≤ 100
  • Time Complexity: O(n) for each traversal
  • Space Complexity: O(n) for recursion stack and result arrays
RecursionBinary TreePwCD. E. Shaw
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 all three traversals
  • For inorder: recursively traverse left, visit root, recursively traverse right
  • For preorder: visit root, recursively traverse left, recursively traverse right
  • For postorder: recursively traverse left, recursively traverse right, visit root
  • Use arrays to store the traversal results and return them

Steps to solve by this approach:

 Step 1: Create a result array to store the traversal order for each method.
 Step 2: Define recursive helper functions for each traversal type.
 Step 3: Handle base case - return if current node is null.
 Step 4: For inorder: recursively traverse left, add current value, recursively traverse right.
 Step 5: For preorder: add current value, recursively traverse left, recursively traverse right.
 Step 6: For postorder: recursively traverse left, recursively traverse right, add current value.
 Step 7: Call the helper function with root node and return the result array.

Submitted Code :