Day 16/100 – LeetCode Challenge Problem Solved: Binary Tree Level Order Traversal Today’s problem focused on traversing a binary tree level by level. Instead of visiting nodes in depth-first order, the goal is to group nodes according to their depth in the tree. The idea behind the solution is to track the level of each node while traversing the tree. Starting from the root at level 0, each recursive call increases the level for its child nodes. When visiting a node, we check whether a list for that level already exists. If not, we create one; otherwise, we append the node value to the existing level list. By doing this, the traversal naturally organizes nodes into separate lists representing each level of the tree. Time Complexity: O(n) Space Complexity: O(n) Key takeaway: Tree problems often become easier when you track additional context during traversal. In this case, maintaining the current level allows the recursion to build a structured level-by-level result. Day 16 completed. Continuing the consistency streak and strengthening tree traversal concepts. #100DaysOfLeetCode #Java #BinaryTree #TreeTraversal #Algorithms #ProblemSolving
Binary Tree Level Order Traversal Solution
More Relevant Posts
-
Day 18/100 – LeetCode Challenge Problem Solved: Reverse Linked List Today’s problem focused on reversing a singly linked list. While it looks simple, it’s a fundamental concept that tests pointer manipulation and understanding of linked structures. The idea is to iterate through the list and reverse the direction of each node’s pointer. At every step, we keep track of three things: the current node, the previous node, and the next node. We reverse the link by pointing the current node to the previous one, then move all pointers one step forward. By the end of the traversal, the previous pointer will be pointing to the new head of the reversed list. Time Complexity: O(n) Space Complexity: O(1) Performance: Runtime 0 ms Key takeaway: Linked list problems are all about pointer control. Mastering how pointers move and change direction is essential for solving more complex problems efficiently. Day 18 completed. Staying consistent and reinforcing core data structure fundamentals. #100DaysOfLeetCode #Java #LinkedList #Algorithms #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
🚀 Day 55/100: LeetCode Challenge – Path Sum (Binary Trees) Halfway through the 100-day journey and the momentum is only building! Today’s focus was on Binary Trees and recursion with the "Path Sum" problem. 💡 The Logic The goal is to determine if a tree has a root-to-leaf path that sums up to a specific targetSum. My approach used a recursive Depth-First Search (DFS): Base Case: If the node is null, return false. Leaf Check: If we reach a leaf node, check if the remaining sum equals the node's value. Recursion: Subtract the current node's value from the target and move down to the left and right children. 📊 Results Runtime: 0 ms (Beats 100.00% of Java users) ⚡ Memory: 44.74 MB (Beats 89.55% of Java users) 🧠 Recursive solutions for trees always feel like magic when they click. It’s all about breaking down a complex structure into the simplest possible sub-problem. Onward to Day 56! #LeetCode #100DaysOfCode #Java #DataStructures #Algorithms #SoftwareEngineering #BinaryTree #CodingChallenge
To view or add a comment, sign in
-
-
Today I solved LeetCode 104 – Maximum Depth of Binary Tree. 🧩 Problem Summary: Given the root of a binary tree, return its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 💡 Key Concepts Used: Binary Trees Recursion Depth First Search (DFS) Tree traversal 🧠 Approach: Use DFS (recursion) to explore the tree. For each node: Recursively calculate the depth of the left subtree. Recursively calculate the depth of the right subtree. The depth of the current node = 1 + max(left depth, right depth) Base case: if node is null, return 0. ⏱ Time Complexity: O(N) — Each node is visited once. 📚 What I Learned: Understanding tree depth calculation. Strengthening recursion and DFS concepts. Difference between maximum depth vs minimum depth. Building intuition for tree-based problems. Strong fundamentals in trees make advanced problems easier Consistency is the key to improvement #LeetCode #DSA #BinaryTree #MaximumDepth #DFS #Recursion #Java #CodingJourney #ProblemSolving #100DaysOfCode #TechGrowth
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
-
-
I just solved LeetCode 662: Maximum Width of Binary Tree! Finding the width is different from a normal traversal because you have to account for the empty spaces between nodes. I used a simple indexing trick ($2i+1$ and $2i+2$) and an ArrayDeque to track positions. By using peekFirst() and peekLast(), I could instantly calculate the width of each level ($right - left + 1$). It’s a great example of how choosing the right data structure makes the logic much cleaner! #LeetCode #Java #BinaryTree #Coding
To view or add a comment, sign in
-
Day 17/100 – LeetCode Challenge Problem Solved: Spiral Matrix Today’s problem required traversing a matrix in spiral order, starting from the top-left corner and moving right, down, left, and up repeatedly until all elements are visited. The key idea is to maintain four boundaries that represent the current layer of the matrix being processed: top, bottom, left, and right. We move in four directions step by step: ->Traverse from left to right across the top row. ->Traverse from top to bottom along the right column. ->Traverse from right to left across the bottom row. ->Traverse from bottom to top along the left column. After completing each direction, the corresponding boundary is adjusted inward so the traversal continues with the inner layer of the matrix. This process continues until the boundaries cross, ensuring every element is visited exactly once. Time Complexity: O(m × n) Space Complexity: O(1) (excluding the result list) Performance: Runtime 0 ms Key takeaway: Many matrix traversal problems become manageable when you define clear boundaries and shrink them step by step. Day 17 completed. Continuing the journey of strengthening algorithmic thinking through consistent practice. #100DaysOfLeetCode #Java #Algorithms #MatrixTraversal #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
🔥 Day 36 of #75DaysofLeetCode 🔥 LeetCode 437 – Path Sum III | Prefix Sum + DFS Magic! Struggled with counting paths in a binary tree that sum up to a target? 🤔 This problem looks like a typical tree traversal… but the optimal solution is 🔥 next-level thinking. 💡 Problem Insight: We need to count all paths (not necessarily from root) where the sum equals targetSum. Condition → Path must go downwards (parent → child). 🚫 Brute Force Idea: Start DFS from every node → check all paths ⏱️ Time Complexity: O(n²) (not efficient) ⚡ Optimized Approach: Prefix Sum + HashMap Instead of recomputing sums, we: ✔ Maintain a running sum (currentSum) ✔ Store previous sums in a HashMap ✔ Check if (currentSum - targetSum) exists 👉 This tells us how many valid paths end at the current node! 🧠 Core Logic: Add current node value to currentSum Check: currentSum - targetSum in map Update map before recursion Backtrack after recursion ⏱️ Complexity: Time: O(n) Space: O(n) 🚀 Key Takeaway: Whenever you see: 👉 "subarray sum = k" or 👉 "path sum = target" Think Prefix Sum + HashMap 💡 #LeetCode #DSA #Java #CodingInterview #BinaryTree #Programming #SoftwareEngineering #100DaysOfCode
To view or add a comment, sign in
-
-
✳️Day 20 of #100DaysOfCode✳️ 🚀 New Problem Solved: Largest Subarray with 0 Sum! 🛠️ The Logic Behind the Code: To solve this efficiently, I used a HashMap to track prefix sums and their first occurrences. Here are the key steps I followed: Prefix Sum Tracking: As I iterate through the array, I maintain a running sum of the elements. The Base Case: If the sum itself becomes 0 at any point, the subarray from the very beginning to the current index i has a sum of 0. I update the max length to i + 1. Hashing for Efficiency: If the current sum has been seen before in the HashMap, it means the elements between the previous occurrence and the current index must add up to 0. I calculate the distance (current\_index - previous\_index) and update my maxLen. Storing New Sums: If the sum is new, I store it in the map with its index to ensure I always calculate the largest possible distance later. Complexity: Time: O(n) — We only traverse the array once. Space: O(n) — To store the prefix sums in the Map. #DataStructures #Algorithms #Java #CodingLife #GeeksforGeeks #ProblemSolving #SoftwareEngineering
To view or add a comment, sign in
-
-
🔥 Day 59/100 – LeetCode Challenge 📌 Problem Solved: Remove Duplicates from Sorted Array II (Medium) Today’s problem was a great exercise in in-place array manipulation and two-pointer technique. 💡 Key Idea: Since the array is already sorted, duplicates are adjacent. Instead of removing all duplicates, we allow each element to appear at most twice. 👉 The trick is to compare the current element with the element at index k-2. If they are the same → skip ❌ If different → keep it ✅ ⚙️ Approach: Initialize pointer k = 2 Traverse from index 2 Copy valid elements forward Maintain order without extra space 🧠 What I learned: How to efficiently handle constraints like “at most twice” Importance of thinking in terms of index relationships (k-2) Writing optimal O(n) solutions with O(1) space 📊 Performance: ⚡ Runtime: 0 ms (100%) 💾 Memory: 48.46 MB 💻 Tech Used: Java Consistency is key 🔑 — 59 days done, 41 more to go! #100DaysOfCode #LeetCode #Java #DataStructures #CodingChallenge #ProblemSolving #TechJourney
To view or add a comment, sign in
-
-
🚀 Day 44 of #100DaysOfCode Solved 1011. Capacity To Ship Packages Within D Days on LeetCode 📦 🧠 Key Insight: We need to find the minimum ship capacity such that all packages can be shipped within D days. This is a classic case of Binary Search on Answer. ⚙️ Approach: 1️⃣ The minimum capacity = max(weight) (since one package must fit) 2️⃣ The maximum capacity = sum of all weights 3️⃣ Apply Binary Search between these bounds 4️⃣ For each capacity mid, simulate shipping: 🔹Keep adding weights until capacity exceeds 🔹Move to the next day when exceeded 5️⃣ If we can ship within D days → try smaller capacity 6️⃣ Else → increase capacity This helps us find the minimum valid capacity efficiently. ⏱️ Time Complexity: O(n log(sum)) 📦 Space Complexity: O(1) #100DaysOfCode #LeetCode #DSA #BinarySearch #Algorithms #Java #InterviewPrep #CodingJourney
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