🧠 Day 36/75: Recursion within Recursion! Today’s challenge was "Subtree of Another Tree," a problem that perfectly illustrates how we can reuse fundamental patterns to solve more complex structures. The Strategy: To solve this, I combined two recursive ideas: Traverse the Main Tree: A standard DFS to visit every node in the primary tree. Structural Comparison: At every node, I used a helper function (isSameTree) to check if the current subtree perfectly matches the target structure. Performance: ✅ Runtime: 3 ms (Beats 67.99% of Java users) ✅ Complexity: $O(M \times N)$ in the worst case, but highly efficient for most tree structures. It’s incredibly satisfying to see yesterday's "Same Tree" logic become just one small part of today's larger solution. Build, repeat, and scale! 🚀 #LeetCode #75DaysOfCode #Java #BinaryTree #Recursion #DSA #SoftwareEngineering #ProblemSolving
Solving Subtree of Another Tree with Recursion
More Relevant Posts
-
Day 9/ #100DaysOfCode Solved LeetCode 1848: Minimum Distance to the Target Element. Approach: The problem can be solved using a straightforward linear traversal. Iterate through the array and check for indices where the value equals the target. For each such index, compute the absolute difference between the current index and the given start index. Maintain a variable to track the minimum distance encountered during the traversal. Solution Insight: Initialize a variable with a large value (e.g., Integer.MAX_VALUE). Traverse the array once. Whenever the target element is found, update the minimum distance using Math.abs(i - start). Return the minimum value after the loop. Complexity: Time Complexity: O(n) Space Complexity: O(1) Result: 72/72 test cases passed with optimal runtime performance. This problem reinforces the importance of simple iteration and careful tracking of minimum values in array-based problems. #100DaysOfCode #LeetCode #DSA #Java #ProblemSolving #Algorithms
To view or add a comment, sign in
-
-
Day 74 - Univalued Binary Tree Checking whether all nodes in a binary tree share the same value using recursion. Approach: • Store root value • Traverse the tree recursively • Compare each node with root value • Return false if any mismatch is found Key Insight: Recursion simplifies tree traversal and validation Time Complexity: O(n) #Day74 #LeetCode #Java #CodingPractice #TechJourney #DSA #BinaryTree
To view or add a comment, sign in
-
-
Day 70 - Next Greater Node Understanding how to find the next larger value for each node using stack optimization. Approach: • Convert linked list → array for easy indexing • Use a stack to track indices • Compare current value with stack top • Update results when a greater value is found Key Insight: Monotonic stack helps avoid unnecessary comparisons Time Complexity: O(n) Space Complexity: O(n) #Day70 #LeetCode #Java #CodingPractice #TechJourney #DSA #LinkedList
To view or add a comment, sign in
-
-
Day 114 - LeetCode Journey Solved LeetCode 572 – Subtree of Another Tree ✅ This problem focuses on determining whether one binary tree is a subtree of another. A subtree must match both in structure and node values, which makes it more than just a simple value comparison problem. Approach: I used a recursive strategy combining two key steps: Traverse each node of the main tree At every node, check if the subtree starting from that node is identical to the given subRoot For checking identical trees, I implemented a helper function that compares: • Node values • Left subtree • Right subtree If all match, we confirm the subtree exists. Otherwise, we continue searching in the left and right branches of the main tree. Complexity Analysis: • Time Complexity: O(n × m) in the worst case, where n is nodes in root and m is nodes in subRoot • Space Complexity: O(h), due to recursion stack Key Takeaways: • Tree problems often require combining traversal + comparison logic • Breaking problems into helper functions simplifies implementation • Understanding recursion flow is crucial for tree-based questions 🌳 All test cases passed successfully 🎯 #LeetCode #DSA #BinaryTree #Recursion #Java #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
Day 113 - LeetCode Journey Solved LeetCode 222 – Count Complete Tree Nodes ✅ This problem involves counting the total number of nodes in a complete binary tree, where all levels are fully filled except possibly the last, and nodes are as far left as possible. Approach: I implemented a recursive solution to count nodes. For each node, I recursively calculated the number of nodes in the left and right subtrees and added 1 for the current node. Although this solution works correctly, it follows a straightforward traversal approach and does not fully utilize the properties of a complete binary tree. A more optimized approach can reduce time complexity by comparing left and right subtree heights to detect perfect subtrees and compute their node count directly. Complexity Analysis: • Time Complexity: O(n) • Space Complexity: O(h), where h is the height of the tree (recursion stack) Key Takeaways: • Basic tree traversal (DFS) can solve counting problems effectively • Understanding tree properties can help in optimizing solutions further • Complete binary trees allow more efficient approaches than general trees All test cases passed successfully 🎯 #LeetCode #DSA #BinaryTree #Recursion #Java #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
Day 72/100 Completed ✅ 🚀 Solved LeetCode – Matrix Diagonal Sum (Java) ⚡ Implemented an efficient approach to calculate the sum of both primary and secondary diagonals of a square matrix in a single traversal. Avoided double-counting the center element by handling the odd-sized matrix case separately. 🧠 Key Learnings: • Efficient diagonal traversal in a matrix • Handling overlapping elements (center in odd n) • Writing optimal O(n) solutions instead of nested loops • Clean and concise index-based logic 💯 This problem improved my understanding of matrix patterns and how to optimize traversal by reducing unnecessary iterations. 🔗 Profile: https://lnkd.in/gaJmKdrA #leetcode #datastructures #algorithms #java #matrix #arrays #problemSolving #100DaysOfCode 🚀
To view or add a comment, sign in
-
-
Day 71/100 Completed ✅ 🚀 Solved LeetCode – Reshape the Matrix (Java) ⚡ Implemented an efficient matrix transformation approach by mapping elements from the original matrix to the reshaped matrix using a single traversal. Instead of creating intermediate structures, used index manipulation (count / c, count % c) to place elements correctly while maintaining row-wise order. 🧠 Key Learnings: • Understanding how to map 2D indices into a linear traversal • Efficiently converting between different matrix dimensions • Handling edge cases where reshape is not possible • Writing clean and optimized nested loop logic 💯 This problem strengthened my understanding of matrix traversal and index mapping techniques, which are very useful in array and grid-based problems. 🔗 Profile: https://lnkd.in/gaJmKdrA #leetcode #datastructures #algorithms #java #matrix #arrays #problemSolving #100DaysOfCode 🚀
To view or add a comment, sign in
-
-
Day 90 - LeetCode Journey Solved LeetCode 2181: Merge Nodes in Between Zeros in Java ✅ This problem is all about smart traversal and building a new linked list on the go. I used a dummy node + running sum approach. As I traversed the list, I kept adding values until I hit a zero. Once a zero appeared, I created a new node with the accumulated sum and reset the sum for the next segment. Clean, intuitive, and efficient. Key takeaways: • Using dummy node to simplify list construction • Handling segments using running sum • Clean traversal without extra data structures • Strong understanding of linked list manipulation ✅ All test cases passed ⚡ O(n) time and O(1) extra space Problems like this improve your ability to think in segments and patterns 🔥 #LeetCode #DSA #Java #LinkedList #ProblemSolving #CodingJourney #InterviewPrep #Consistency #100DaysOfCode
To view or add a comment, sign in
-
-
Day 68/100 Completed ✅ 🚀 Solved LeetCode – Split Array Largest Sum (Java) ⚡ Applied an efficient Binary Search on Answer approach to split the array into k subarrays such that the largest subarray sum is minimized. Instead of trying all possible splits, optimized the solution by searching within the range of maximum element and total sum, and validating using a greedy strategy. 🧠 Key Learnings: Identifying binary search applicability in partition-based problems Defining search space using max element (lower bound) and total sum (upper bound) Using greedy logic to check feasibility of splitting into k subarrays Minimizing the maximum subarray sum through efficient validation 💯 This problem strengthened my understanding of partition problems and reinforced how binary search can be used for optimization rather than direct searching. 🔗 Profile: https://lnkd.in/gaJmKdrA #leetcode #datastructures #algorithms #java #binarysearch #problemSolving #100DaysOfCode
To view or add a comment, sign in
-
-
💡 Day 55 of LeetCode Problem Solved! 🔧 🌟21. Merge Two Sorted Lists🌟 🔗 Solution Code: https://lnkd.in/gU7m-4wH 🧠 Approach: • Recursive Merge • Checked for null node base cases to identify the ends of the lists. • Recursively compared the current node values of list1 and list2. • Attached the smaller node to point to the recursively merged result of the remaining nodes. ⚡ Key Learning: • Leveraging recursion drastically simplifies Linked List operations, turning complex pointer-splicing logic into an elegant and readable sequence! ⏱️ Complexity: Time: • O(n + m) — where n and m are the lengths of the two lists Space. • O(n + m) — due to the recursion stack #LeetCode #Java #DSA #ProblemSolving #Consistency #100DaysOfCode #CodingJourney #LinkedList #Recursion
To view or add a comment, sign in
-
Explore related topics
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