
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.
- The tree has root 1, right child 2, and 2 has left child 3.
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.
- This is a complete binary tree with 7 nodes.
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
Editorial
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. |
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