🚀 07/03/26 — Leveling Up: Mastering Binary Tree Level Order Traversal Today's session was all about shifting from depth-based exploration to breadth-based traversal. I implemented the Level Order Traversal (LeetCode 102), which is the foundation for Breadth-First Search (BFS) in trees. 🌊 Level Order Traversal (BFS) Unlike Preorder or Inorder which dive deep into branches, Level Order visits the tree layer by layer, from top to bottom and left to right. The Logic: Initialize a Queue to keep track of nodes at the current and next levels. Add the root to the queue to start. The Level-By-Level Strategy: Inside the main while loop, I capture the current size of the queue. This ensures that I only process nodes belonging to the current level before moving to the next. For each node processed, add its value to the current level list and enqueue its left and right children if they exist. Complexity: Time: O(N) because every node is enqueued and dequeued exactly once. Space: O(N) to hold the queue, which at most contains the maximum width of the tree. 📊 Implementation Highlights FeaturePreorder/Inorder (Yesterday)Level Order (Today)StrategyDepth-First Search (DFS)Breadth-First Search (BFS)Data StructureStack (FILO)Queue (FIFO)Traversal PathFollows branches to the leafVisits layer by layer📈 Consistency Report Applying the Queue implementation I practiced on March 2nd to a Binary Tree problem was a perfect example of how different DSA topics connect. Using the size() of the queue to separate levels is a key interview pattern that I now feel very comfortable with. Huge thanks to Anuj Kumar (a.k.a CTO Bhaiya on YouTube) for the roadmap. Moving from depth-based logic to breadth-based flows is a major expansion of my tree-solving toolkit! My tested implementation for Level Order Traversal is attached! 📄👇 #DSA #Java #LeetCode #BinaryTree #BFS #Queue #CodingJourney #LevelOrderTraversal #LearningInPublic #CTOBhaiya
Mastering Binary Tree Level Order Traversal with BFS
More Relevant Posts
-
Today I solved LeetCode 145 – Binary Tree Postorder Traversal. 🧩 Problem Summary: Given the root of a binary tree, return the postorder traversal of its nodes' values. In postorder traversal, nodes are visited in the order: Left → Right → Root 💡 Key Concepts Used: Binary Trees Tree Traversal Iterative approach using Stack Depth First Search (DFS) 🧠 Approach: Use a stack to simulate recursion. Traverse to the leftmost node while pushing nodes onto the stack. Peek the node at the top of the stack. If the node has a right child that hasn’t been processed, move to the right subtree. Otherwise, process the node (add it to the result) and mark it as last visited. Repeat until all nodes are processed. This ensures the correct Left → Right → Root traversal order. 📚 What I Learned: How to implement postorder traversal iteratively. Managing traversal state using a stack and lastVisited pointer. Understanding the difference between recursive and iterative tree traversal. Strengthening concepts of Depth First Search (DFS) in binary trees. Exploring tree problems to build a stronger DSA foundation 🌳 Consistency in learning every day 🚀 #LeetCode #DSA #BinaryTree #TreeTraversal #PostorderTraversal #Stack #Java #CodingJourney #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
-
Today I solved LeetCode 145 – Binary Tree Postorder Traversal. 🧩 Problem Summary: Given the root of a binary tree, return the postorder traversal of its nodes' values. In postorder traversal, nodes are visited in the order: Left → Right → Root 💡 Key Concepts Used: Binary Trees Tree Traversal Iterative approach using Stack Depth First Search (DFS) 🧠 Approach: Use a stack to simulate recursion. Traverse to the leftmost node while pushing nodes onto the stack. Peek the node at the top of the stack. If the node has a right child that hasn’t been processed, move to the right subtree. Otherwise, process the node (add it to the result) and mark it as last visited. Repeat until all nodes are processed. This ensures the correct Left → Right → Root traversal order. 📚 What I Learned: How to implement postorder traversal iteratively. Managing traversal state using a stack and lastVisited pointer. Understanding the difference between recursive and iterative tree traversal. Strengthening concepts of Depth First Search (DFS) in binary trees. Exploring tree problems to build a stronger DSA foundation 🌳 Consistency in learning every day 🚀 #LeetCode #DSA #BinaryTree #TreeTraversal #PostorderTraversal #Stack #Java #CodingJourney #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
-
Day 66 - LeetCode Journey Solved LeetCode 167: Two Sum II – Input Array Is Sorted (Medium) today — a great example of how knowing the properties of a sorted array can drastically simplify the solution. Since the array is already sorted in non-decreasing order, we can avoid extra data structures and use a two-pointer approach to find the pair efficiently. 💡 Core Idea: Start with two pointers: • left at the beginning • right at the end Then check the sum of the two numbers: If the sum is equal to the target → solution found If the sum is less than the target → move the left pointer forward If the sum is greater than the target → move the right pointer backward This gradually narrows down the search space until the correct pair is found. ⚡ Key Learning Points: • Leveraging sorted array properties • Efficient use of the two-pointer technique • Reducing time complexity to O(n) • Solving the problem with O(1) extra space Problems like this highlight how choosing the right technique can make solutions clean, fast, and elegant. ✅ Stronger understanding of two-pointer patterns ✅ Better optimization mindset ✅ Improved problem-solving intuition Every problem solved adds another useful pattern to the toolkit 🚀 #LeetCode #DSA #Java #TwoPointers #Algorithms #ProblemSolving #CodingJourney #Consistency #100DaysOfCode #InterviewPreparation #DeveloperJourney #KeepCoding
To view or add a comment, sign in
-
-
🚀 Day 42 of #100DaysOfCode Solved 1508. Range Sum of Sorted Subarray Sums on LeetCode 📊 🧠 Problem Insight: Given an array, we must compute the sum of all subarray sums, sort them, and return the sum of elements between indices left and right. ⚙️ Approach Used: 1️⃣ Generate all possible subarray sums using nested loops 2️⃣ Store them in an array of size n*(n+1)/2 3️⃣ Sort the subarray sums 4️⃣ Compute the sum of elements from index left-1 to right-1 5️⃣ Apply mod = 1e9 + 7 to avoid overflow This approach works well because the total number of subarrays is manageable for the given constraints. ⏱️ Time Complexity: O(n² log n) O(n²) to generate subarray sums O(n² log n) to sort them 📦 Space Complexity: O(n²) #100DaysOfCode #LeetCode #DSA #Arrays #Algorithms #Java #CodingPractice #InterviewPrep
To view or add a comment, sign in
-
-
🚀 100 Days of Code Day-25 LeetCode Problem Solved: Reverse Nodes in k-Group I recently worked on a Linked List problem that focuses on reversing nodes in groups of size k while preserving the remaining structure if the group size is less than k. 🔹 Strengthened my understanding of pointer manipulation 🔹 Improved problem decomposition skills 🔹 Practiced recursive thinking for efficient implementation 💡 Key takeaway: Breaking complex problems into smaller, manageable parts significantly simplifies the solution approach. Continuing to build consistency in problem-solving and deepen my understanding of Data Structures & Algorithms. #LeetCode #DataStructures #Algorithms #Java #ProblemSolving #SoftwareDevelopment
To view or add a comment, sign in
-
-
🚀 Day 88 of DSA Problem Solving 💡 Problem Solved: Two Sum II – Input Array Is Sorted 🔍 Problem Idea: Given a sorted array, find two numbers such that they add up to a target. Return their indices (1-based). 🧠 Key Learning: Instead of using HashMap (like in classic Two Sum), we can optimize using the **Two Pointer Approach** because the array is already sorted. ⚡ Concepts Practiced: * Two Pointer Technique * Array Traversal * Greedy Decision Making ⏱ Time Complexity: O(n) 💾 Space Complexity: O(1) 🚀 Approach: * Start with two pointers: one at the beginning and one at the end * If sum is too small → move left pointer forward * If sum is too large → move right pointer backward * If sum matches target → return indices 🔥 Real Journey Behind Solution: Initially, I thought of using HashMap (habit from Two Sum 😅), but then realized the sorted property is a huge advantage. Switching mindset to use **two pointers** made the solution cleaner and more optimal. This problem reminded me: 👉 Always look for constraints like “sorted” — they often unlock better solutions. 📌 Takeaway: Smart observation > brute force #Day88 #DSA #LeetCode #Java #CodingJourney #ProblemSolving #TechGrowth #TwoPointers
To view or add a comment, sign in
-
-
🚀 Day 12 of My LeetCode Journey Today I solved Group Anagrams (LeetCode 49). Problem: Given an array of strings, group the strings that are anagrams of each other. Approach: I used a HashMap to group words based on their sorted characters. If two words have the same sorted form, they belong to the same anagram group. Example: "eat", "tea", and "ate" → sorted form "aet" → same group. Key Concepts: • HashMap • String sorting • Hashing technique for grouping Time Complexity: O(n × k log k) Space Complexity: O(n × k) This problem is a great example of using hashing to classify data efficiently. #leetcode #datastructures #algorithms #java #codinginterview #softwareengineering
To view or add a comment, sign in
-
-
𝐃𝐚𝐲 𝟓𝟕 – 𝐃𝐒𝐀 𝐉𝐨𝐮𝐫𝐧𝐞𝐲 | 𝐀𝐫𝐫𝐚𝐲𝐬 🚀 Today’s problem focused on finding the maximum gap between consecutive elements in sorted order — without actually sorting. 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐒𝐨𝐥𝐯𝐞𝐝 • Maximum Gap 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡 – 𝐁𝐮𝐜𝐤𝐞𝐭 𝐒𝐨𝐫𝐭 𝐈𝐝𝐞𝐚 • Found global minimum and maximum • Calculated minimum possible gap using: gap = ceil((max − min) / (n − 1)) • Created buckets to store min and max values • Placed elements into buckets based on their range • Final answer comes from the gap between buckets, not inside them 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠𝐬 • Sorting is not always required to find ordered differences • Bucket strategy helps achieve linear time • Maximum gap always lies between buckets, not within • Mathematical insights (pigeonhole principle) guide optimization 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲 • Time: O(n) • Space: O(n) 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲 Sometimes the problem is not about sorting — but about understanding how elements are distributed. 57 days consistent 🚀 On to Day 58. #DSA #Arrays #BucketSort #LeetCode #Java #ProblemSolving #DailyCoding #LearningInPublic #SoftwareDeveloper
To view or add a comment, sign in
-
-
Day 70 - LeetCode Journey Solved LeetCode 88: Merge Sorted Array (Easy) today — a classic problem that focuses on array manipulation and the two-pointer technique. The challenge is to merge two sorted arrays into one sorted array without using extra space, by modifying nums1 in-place. 💡 Core Idea: Instead of merging from the beginning, we start from the end of the arrays. Why? Because nums1 already has extra space at the end to accommodate elements from nums2. We use three pointers: • i → last valid element in nums1 • j → last element in nums2 • k → last position of merged array At each step, we place the larger element at position k, ensuring the array remains sorted. ⚡ Key Learning Points: • Using the two-pointer technique from the end • Performing in-place array merging • Maintaining O(m + n) time complexity • Avoiding unnecessary extra space This problem is a great reminder that sometimes changing the direction of traversal makes the solution much simpler. ✅ Better understanding of array manipulation ✅ Stronger grasp of two-pointer techniques ✅ Improved problem-solving efficiency Small problems like this build strong fundamentals for bigger challenges 🚀 #LeetCode #DSA #Java #TwoPointers #Arrays #Algorithms #ProblemSolving #CodingJourney #Consistency #100DaysOfCode #InterviewPreparation #DeveloperGrowth #KeepCoding
To view or add a comment, sign in
-
-
Day 52 – DSA Journey 🚀 | Mastering Array Intersection Continuing my daily DSA practice, today I solved an interesting array intersection problem on LeetCode that helped strengthen my understanding of sorting and pointer-based traversal. 📌 Problem Practiced: Intersection of Two Arrays II (LeetCode 350) 🔍 Problem Idea: We are given two integer arrays and need to return their intersection. Each element in the result should appear as many times as it occurs in both arrays. 💡 Key Insight: By sorting both arrays first, we can efficiently compare elements using the two-pointer technique to find common values. 📌 Approach Used: • Sort both arrays to make comparison easier • Use two pointers to traverse the arrays • If elements are equal, add them to the result and move both pointers • If one element is smaller, move that pointer forward • Store the results in a list and convert it into an array at the end 📌 Concepts Strengthened: • Sorting arrays • Two-pointer technique • Efficient element comparison • Converting ArrayList to array in Java ⏱️ Time Complexity: O(n log n + m log m) 📦 Space Complexity: O(k) Today’s takeaway: Combining sorting with the two-pointer technique is a powerful strategy for solving many array comparison problems efficiently. On to Day 53! 🚀 #Day52 #DSAJourney #LeetCode #Arrays #TwoPointers #Java #ProblemSolving #LearningInPublic #Consistency
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development