🔹 Problem: Binary Tree Inorder Traversal Day 122 🔹 Difficulty: Easy 🔹 Topic: Binary Tree / Morris Traversal / Iterative Traversal 🔍 Problem Breakdown: We are given the root of a binary tree, and we need to return the inorder traversal of its nodes’ values. 📘 Inorder Traversal: Left → Root → Right Usually, this can be solved using recursion or stack, but today’s approach uses Morris Traversal, which is O(1) extra space and does not use recursion or stack. 🧠 Approach (Morris Traversal): Start with the current node = root. If the left child is NULL, visit the node and move right. Else, find the inorder predecessor (rightmost node in the left subtree). If predecessor’s right is NULL, make a temporary link to the current node and move left. If predecessor’s right is current, remove the link, visit current node, and move right. Continue until all nodes are visited. This method avoids recursion and stack by establishing temporary links in the tree. ⏱️ Time & Space Complexity: Time Complexity: O(n) — each edge is visited twice. Space Complexity: O(1) — no recursion or stack used. 💡 Key Insight: Morris Traversal is a brilliant way to traverse binary trees in constant space, by cleverly using tree links as temporary pointers — elegant and efficient! #LeetCode #DSA #BinaryTree #MorrisTraversal #InorderTraversal #ProblemSolving #CodingChallenge #200DaysOfCode #Cplusplus
"Morris Traversal: Inorder Traversal without Recursion or Stack"
More Relevant Posts
-
🔗 Day 75 of #100DaysOfCode 🔗 🌳 Problem: Binary Tree Postorder Traversal – LeetCode ✨ Approach: Implemented a recursive depth-first traversal that processes the left subtree, then right subtree, and finally the root node — perfectly matching the postorder pattern (Left → Right → Root). The solution is clean, intuitive, and highlights the elegance of recursion in tree traversal! 🌿 📊 Complexity Analysis: ⏱ Time Complexity: O(n) — each node is visited exactly once 💾 Space Complexity: O(n) — recursion stack in the worst case (skewed tree) ✅ Runtime: 0 ms (Beats 100% 🚀) ✅ Memory: 43.07 MB 💡 Key Insight: Recursion beautifully mirrors the natural hierarchy of trees — by trusting the call stack, we achieve simplicity and clarity in solving even complex traversal problems. 🌱 #LeetCode #100DaysOfCode #ProblemSolving #DSA #BinaryTree #Recursion #AlgorithmDesign #CodeJourney #ProgrammingChallenge #LogicBuilding #Efficiency #CodingDaily
To view or add a comment, sign in
-
-
🔍 Day 66 of #100DaysOfCode 🔍 🔹 Problem: Binary Search – LeetCode ✨ Approach: Implemented an iterative binary search to efficiently locate the target element within a sorted array. By halving the search range each time — adjusting low and high around the mid-point — the algorithm achieves blazing-fast lookups! ⚡ 📊 Complexity Analysis: Time Complexity: O(log n) — array size halves with each iteration Space Complexity: O(1) — constant extra space ✅ Runtime: 0 ms (Beats 100.00%) ✅ Memory: 46.02 MB 🔑 Key Insight: Binary Search is proof that efficiency isn’t about doing more — it’s about eliminating what’s unnecessary. 🚀 #LeetCode #100DaysOfCode #ProblemSolving #DSA #AlgorithmDesign #BinarySearch #LogicBuilding #Efficiency #ProgrammingChallenge #CodeJourney #CodingDaily
To view or add a comment, sign in
-
-
🚀 Day 68 of #100DaysOfLeetcodeHard — LeetCode 2382: Maximum Segment Sum After Removals (Hard) My Submission:https://lnkd.in/g-X4k2Hd Today’s challenge was a Disjoint Set Union (Union-Find) problem with a clever reverse processing approach. 🧩 Problem Summary: We start with an array and remove elements one by one, needing to track the maximum segment sum of contiguous non-removed elements after each removal. Instead of simulating removals forward (which is difficult to track), we reverse the process — ✅ Start from an empty array and add elements back in reverse order. ✅ Use Union-Find (Disjoint Set) to merge adjacent active segments and maintain their sums dynamically. 💡 Approach: Each index starts as its own segment with rank[i] = nums[i] (used to store segment sums). When a new index is added, we union it with its active neighbors (if any). Track the maximum segment sum after each merge. 🧠 Key Concepts Used: Union-Find with path compression & rank to efficiently merge contiguous segments. Reverse iteration to avoid handling splits directly. 📈 Complexity: Time: O(n α(n)) ≈ O(n) (inverse Ackermann function for DSU) Space: O(n) A beautiful mix of data structures + reverse simulation + problem insight — one of those problems that truly sharpen algorithmic thinking. ⚡ #LeetCode #UnionFind #DSU #ProblemSolving #AlgorithmDesign #DataStructures #CodingChallenge #100DaysOfCode #LearningEveryday
To view or add a comment, sign in
-
-
🚀LeetCode Daily Challenge 🧩 Problem: Number of Substrings With Only 1s Problem Intuition: You are given a binary string s. Your task is to count how many non-empty substrings contain only ‘1’s. A key observation is that every continuous segment of 1s contributes multiple substrings. For a segment of length k, the number of substrings formed is: k⋅(k+1)2\frac{k \cdot (k + 1)}{2}2k⋅(k+1)For example, "1" → 1 substring "11" → 3 substrings ("1", "1", "11") "111" → 6 substrings So the goal is to find all consecutive blocks of 1s, compute their contributions, and sum them modulo 109+710^9 + 7109+7. Example Insight: Let’s take an example: s = "110111" Segments: "11" → length = 2 → contributes 3 substrings "111" → length = 3 → contributes 6 substrings Total = 9 substrings that contain only 1s. Approach & Strategy: ✔ Traverse the string and count the length of every consecutive sequence of '1'. ✔ Whenever you hit a '0' or reach the end: • Compute contribution using k(k+1)2\frac{k(k+1)}{2}2k(k+1) • Add to the answer modulo 109+710^9 + 7109+7. ✔ Reset counter and continue. This approach efficiently handles very large strings. 📈 Complexity Analysis: Time Complexity: O(n) — single linear scan Space Complexity: O(1) — constant auxiliary space 🔗 Problem: https://lnkd.in/daKkzfTM 💻 Solution: https://lnkd.in/dReTB6Ab #LeetCode #DSA #Cpp #Strings #Mathematics #ProblemSolving #CodingChallenge #LeetCodeDailyChallenge
To view or add a comment, sign in
-
🚀LeetCode Daily Challenge 🧩 Problem: Make Array Elements Equal to Zero 🔍 Problem Intuition: You’re given an integer array where you can make selections at positions containing 0. Each selection tries to balance the sum of elements to the left and right of that zero. Your task is to count how many such valid selections can make both sides equal or nearly equal (difference of 0 or 1) — leading the entire array toward equilibrium (eventually all zeros). 💡Example Insight: Imagine scanning through each 0 in the array — If the sum of elements on both sides is the same → that position contributes 2 valid ways. If the sums differ by 1 → it contributes 1 valid way. You repeat this for all zeros and count the total valid selections. 🧠 Approach & Strategy: ✔ Traverse through the array and check positions where the element is 0. ✔ For each zero, compute: sum1 = sum of elements to the left (including that zero). sum2 = sum of elements to the right (including that zero). ✔ If |sum1 - sum2| == 0, add 2 to the count. ✔ If |sum1 - sum2| == 1, add 1 to the count. ✔ Return the total count of valid selections. ⚙️ Complexity Analysis: Time Complexity: O(n²) → For each zero, we calculate left and right sums. Space Complexity: O(1) → Only integer variables used. 🔗 Problem: https://lnkd.in/dTKS6N-F 💻 Solution: https://lnkd.in/djxzBeMF #LeetCode #DSA #Cpp #ProblemSolving #CodingChallenge #LeetCodeDailyChallenge
To view or add a comment, sign in
-
🚀LeetCode Daily Challenge 🧩 Problem: Find X-Sum of All K-Long Subarrays I Problem Intuition: You are given an integer array nums and two integers k and x. For every subarray of length k, you must find the X-sum, which is the sum of the top x most frequent elements in that subarray with each element contributing (frequency × element) to the sum. If there are fewer than x distinct elements, you take all available ones. 💡Example Insight: Let nums = [1,1,2,2,3], k = 3, x = 2. Subarrays of length 3 are: [1,1,2], [1,2,2], [2,2,3] For [1,1,2]: Frequencies → {1: 2, 2: 1} Top 2 → (1×2) + (2×1) = 4 So the result for each subarray gives the X-sum pattern accordingly. 🧠 Approach & Strategy: ✔ Use a sliding window of size k to process subarrays efficiently. ✔ Maintain a frequency map (unordered_map<int, int>) for elements inside the current window. ✔ For each valid window: 🔹 Build a max-heap (priority queue) based on element frequencies. 🔹 Pop the top x elements (highest frequencies) and calculate their contribution to the X-sum. ✔ Store the sum in the result vector and slide the window forward. ⚙️ Complexity Analysis: Time Complexity: O(n × log m) → where m is the number of distinct elements in each window. Space Complexity: O(m) → for maintaining the frequency map and heap. 🔗 Problem: https://lnkd.in/dtWEDDrj 💻 Solution: https://lnkd.in/du3Mmi4S #LeetCode #DSA #Cpp #ProblemSolving #CodingChallenge #LeetCodeDailyChallenge
To view or add a comment, sign in
-
Day 29 of #LeetCode Journey — Search a 2D Matrix Today I tackled the “Search a 2D Matrix” problem — a classic example of applying binary search logic beyond 1D arrays. 🧩 Problem in short: Given a sorted 2D matrix (each row sorted, and the first element of each row > last element of the previous row), determine if a target value exists in it. 💡 Intuition: Even though the data is 2D, the sorted structure lets us treat it like a single sorted 1D array. By mapping each 1D index to a (row, col) position using: row = mid / cols col = mid % cols we can perform a standard binary search — cutting down the search space logarithmically. ⚙️ Time Complexity: O(log(m × n)) 📦 Space Complexity: O(1) 🔍 Key Takeaway: This problem reinforces how pattern recognition is more important than brute force. Once you see the sorted structure as a continuous sequence, the solution becomes elegant and efficient. #Day29 #LeetCode #ProblemSolving #BinarySearch #DSA #CodingJourney #CodeEveryday
To view or add a comment, sign in
-
-
🚀 Day 61 | Recursion & Balanced BST Construction Today’s problem focused on building a height-balanced Binary Search Tree from a sorted array — a perfect use case for divide-and-conquer. 🧩 Problem Solved: 108. Convert Sorted Array to Binary Search Tree • Approach: Used recursion — picked the middle element as the root, recursively built left and right subtrees from the halves. • Insight: Balanced trees naturally emerge when you divide sorted data around the midpoint — a great illustration of symmetry in recursion. ✨ Key Takeaway: Recursion mirrors structure — when you trust the process, complex problems unfold with simple, elegant logic. 📚 Topics: Binary Search Tree · Recursion · Divide and Conquer 💻 Platform: LeetCode #DSA #LeetCode #ProblemSolving #DailyCoding #Recursion #BinarySearchTree #Consistency
To view or add a comment, sign in
-
-
🔹 Day 66 of #100DaysOfLeetCodeChallenge 🔹 Problem: Subsets (Power Set) Focus: Backtracking + Recursion 💡 The Challenge: Generate all possible subsets of an array with unique elements. This includes the empty set and the complete set itself! 🧠 My Approach: Implemented backtracking to build subsets incrementally: Start with an empty subset and add it to results For each element, make a choice: include it or skip it Recursively explore all combinations from current index onwards Backtrack by removing the last added element to explore other paths 📊 Complexity Analysis: ⏳ Time: O(n × 2ⁿ) — 2ⁿ subsets, each taking O(n) to copy 💾 Space: O(n) — recursion depth 📌 Example: Input: nums = [1,2,3] Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]] 🎯 Key Takeaway: The power set problem elegantly demonstrates how backtracking can systematically explore all combinations. Each recursive call branches into two possibilities: include or exclude the current element. Classic decision tree visualization! 🌳 Pro tip: This pattern appears in many combinatorial problems — master it once, use it everywhere! Day 66/100 complete. Two-thirds through the journey! 🚀 #LeetCode #Algorithms #Backtracking #PowerSet #DSA #CodingChallenge #TechInterview #SoftwareEngineering #100DaysOfCode #LearnInPublic
To view or add a comment, sign in
-
-
🔹 Day 74 of #100DaysOfLeetCodeChallenge 🔹 🚀 Problem: Next Greater Element II 🔑 Topic: Stack + Circular Array 🧠 Approach: We need to find the next greater element for each item in a circular array. Here’s the logic 👇 Use a monotonic stack to store indices of elements (in decreasing order). Traverse the array twice (2 × n) to simulate circular behavior. Whenever the current element is greater than the element at the stack’s top, pop it and record the next greater value. Push the index during the first pass only. Default all elements to -1 (in case no greater element exists). ⏳ Time Complexity: O(n) 💾 Space Complexity: O(n) 📌 Example: Input: nums = [1,2,1] Output: [2, -1, 2] ✅ 🎯 Takeaway: Monotonic stacks are super efficient for "next greater" problems — linear time, no brute force, and elegant logic! ⚡ #LeetCode #DSA #Stack #MonotonicStack #ProblemSolving #CodingChallenge #100DaysOfLeetCodeChallenge 🚀
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