Reconstructing a Binary Tree from Preorder and Inorder Traversal

🌳 DSA Challenge – Day 100 🎉 Problem: Construct Binary Tree from Preorder and Inorder Traversal 🌲 We made it to Day 100 of the challenge! 💪🔥 Let’s end this journey with a classic Tree Construction problem — a perfect blend of recursion, hashing, and traversal logic. 🧠 Problem Summary: You’re given two integer arrays: preorder → preorder traversal of a binary tree inorder → inorder traversal of the same tree Your goal: Reconstruct and return the binary tree. ⚙️ My Approach: 1️⃣ The first element of preorder is always the root. 2️⃣ Use a hash map (index) to quickly find the root’s position in the inorder array. 3️⃣ Recursively build: The left subtree from elements before the root in inorder. The right subtree from elements after the root in inorder. 4️⃣ Reversing preorder allows efficient pop() operations from the end (O(1)). 💡 Why This Works: Preorder gives the root order, Inorder gives the structure (left–root–right). By combining both, we can rebuild the entire tree recursively in O(n) time. 📈 Complexity Analysis: Time Complexity: O(n) — Each node is processed once, and lookup is O(1) using a hash map. Space Complexity: O(n) — For recursion + hash map. ✨ Key Takeaway: Efficient recursion often comes from using traversal properties smartly — here, preorder identifies roots, while inorder defines subtree boundaries. 🌟 Milestone Moment: That’s Day 100 of DSA 🔥 From arrays to trees, recursion to heaps — what a journey! 🌱 Keep learning, keep building, and keep challenging yourself 💪 🔖 #Day100 #100DaysOfCode #DSA #BinaryTree #Preorder #Inorder #LeetCode #Recursion #Python #DataStructures #ProblemSolving #CodingChallenge #TechCommunity #Milestone

  • text

To view or add a comment, sign in

Explore content categories