✅ Solved LeetCode: Same Tree (100) — Recursive DFS Approach Implemented a clean recursive solution in JavaScript using a structural comparison strategy. Approach: - If both nodes p and q are null, return true. - If only one of them is null, return false. - Otherwise: - Check if p.val === q.val. - Recursively compare: - p.left with q.left - p.right with q.right - Return the combined result of value equality and both subtree comparisons. This approach ensures both structure and node values are identical at every level of the tree. Time Complexity: O(n) — each node is visited once Space Complexity: O(h) — recursion stack space (where h is tree height) A straightforward and elegant recursive pattern for tree comparison problems!
Recursive DFS Solution for Same Tree Problem on LeetCode
More Relevant Posts
-
Day 21: The Final Logic – Closures & The Magic of Property Access 🔒✨ Today marks the grand finale of the JavaScript deep-dive. We didn't just look at the code; we looked at the Memory and the Engine logic that governs how variables live and die. 🧠 The "Crack-It Kit" Checklist: Day 21 📑 🔹 The "Stack Overflow" Trap: Understanding why a setter that calls itself triggers a recursion loop, and the "Underscore Logic" (_variable) used to fix it. 🛡️ 🔹 Getters & Setters: Moving beyond simple data storage to "Smart Properties." Whether using Class syntax or Object.defineProperty, it's about intercepting and validating every piece of data. ⚙️ 🔹 The .length Mystery: Breaking down how arr.length actually works. It’s not just a counter—it’s an exotic property managed by the engine with a setter that can physically truncate memory. 🧪 🔹 Lexical Scoping: Mastering the "Hierarchy of Access." Understanding that where you write your code determines what your functions can see. 🏛️ 🔹 Closures (The Memory Lock): The ultimate interview topic. Learning how JS "locks" parent variables in memory to keep them alive for inner functions, even after the parent has finished executing. 🔒 The JavaScript foundation is now 100% complete. From the TCP 3-way handshake to the internal mechanics of Closures, the logic is locked in. 🏗️ #JavaScript #WebDevelopment #CrackItKit #Closures #WebEngineering #CodingJourney #SoftwareArchitecture #TechInterviews #MERNStack #WanderlustProject
To view or add a comment, sign in
-
-
Q. How does JavaScript handle memory management? Answer: JavaScript uses automatic garbage collection. Main concepts: - Stack → stores primitive values + function calls - Heap → stores objects, arrays, functions Garbage collector uses Mark-and-Sweep algorithm: - Mark reachable objects. - Remove unreachable ones. Memory leak happens when references are kept unintentionally. Example leak in picture * If arr keeps growing → memory leak.
To view or add a comment, sign in
-
-
🚀 𝗡𝗲𝘄 𝗣𝗥 𝗠𝗲𝗿𝗴𝗲𝗱 I recently tackled the challenge of reversing an array in-place. The core 🧩 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 was to modify the original array directly without creating a new one, which requires careful index management. To solve this, I implemented the two-pointer technique in JavaScript. I used one pointer starting at the beginning of the array and another at the end. I then swapped the elements pointed to by these pointers and moved them towards the center until they met or crossed. This ⚙️ 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵 ensures O(1) space complexity. My 🐞 𝗗𝗲𝗯𝘂𝗴𝗴𝗶𝗻𝗴 𝗣𝗿𝗼𝗰𝗲𝘀𝘀 involved dry runs to trace the pointer movements and element swaps. Visualizing the array's state at each step was crucial. I also occasionally used the debugger to step through the code and confirm my understanding of the logic. A 📚 𝗞𝗲𝘆 𝗟𝗲𝗮𝗿𝗻𝗶𝗻𝗴 from this exercise was the power of in-place algorithms for optimizing memory usage, especially when dealing with large datasets. You can see the implementation in my latest PR: https://lnkd.in/d5rAw_CN What are your favorite in-place algorithms or techniques? 📦 Repo: https://lnkd.in/d5rAw_CN #DataStructures #Algorithms #JavaScript #TwoPointerTechnique #ProblemSolving #InPlaceAlgorithm #CodingChallenge #SoftwareDevelopment #ArrayManipulation
To view or add a comment, sign in
-
-
Why did Brenden Eich chosed prototype inheritance instead of class based for JavaScript? Key characteristics of JavaScript are simplicity, flexibility, and dynamic. In class-based inheritance, once an object is created, data and method cannot be added or removed but this is possible in prototype inheritance. Ex :- Adding data const person = { name: "Sohail" }; person.age = 22; Adding method function Animal() {} Animal.prototype.eat = function() {}; const dog = new Animal(); Animal.prototype.sleep = function() {}; dog.sleep(); In prototype, we can add data and methods even after creating object. This makes is flexible and dynamic.
To view or add a comment, sign in
-
📣 𝗡𝗲𝘅𝘁 𝗕𝗹𝗼𝗴 𝗶𝘀 𝗛𝗲𝗿𝗲! ⤵️ Array Methods You Must Know — Writing Less Loops, More Logic ⚡🧠 Working with arrays using only loops feels repetitive. Modern JavaScript gives cleaner tools — and this blog explains them step by step. 🔗 𝗥𝗲𝗮𝗱 𝗵𝗲𝗿𝗲: https://lnkd.in/gqQKdsAc 𝗧𝗼𝗽𝗶𝗰𝘀 𝗰𝗼𝘃𝗲𝗿𝗲𝗱 ✍🏻: ⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺ ⇢ Adding and removing elements using push, pop, shift, unshift ⇢ Looping arrays cleanly with forEach() ⇢ Transforming data using map() ⇢ Filtering values using filter() ⇢ Combining array values using reduce() ⇢ Traditional loops vs modern method chaining ⇢ Real beginner examples and practice assignments ⇢ Common mistakes like forgetting return in map/filter ⇢ Mental model to choose the right method 💬 If arrays still feel like “write loop → do work → repeat”, this article helps you understand how modern array methods make code cleaner, shorter, and easier to reason about. #ChaiAurCode #JavaScript #ArrayMethods #WebDevelopment #ProgrammingBasics #Beginners #LearningInPublic #100DaysOfCoding
To view or add a comment, sign in
-
-
JavaScript’s sort() can silently break your algorithms. I was solving LeetCode #350 (Intersection of Two Arrays II) using the two-pointer approach and hit an unexpected issue. I sorted the arrays like this: nums.sort() It looked fine… until it wasn’t. Example: [1, 2, 10, 5].sort() // → [1, 10, 2, 5] Why? Because JavaScript sorts lexicographically (as strings) by default. So the engine actually compares: "1", "10", "2", "5" Correct numeric sorting requires a comparator: nums.sort((a, b) => a - b) Without this, algorithms that rely on sorted arrays (binary search, two-pointer techniques, etc.) can produce incorrect results. #JavaScript #WebDevelopment #Programming #CodingTips #LeetCode #Algorithms #SoftwareEngineering #FrontendDevelopment
To view or add a comment, sign in
-
-
Solved the Flatten a Multilevel Doubly Linked List problem using a Depth-First Search (DFS) approach in JavaScript. Key idea: Traverse the list and whenever a node contains a child pointer, recursively flatten the child list and splice it into the main list while maintaining proper prev and next connections. This problem is a great exercise in pointer manipulation and recursion. It reinforces how important it is to carefully update references when working with linked data structures. Time complexity: O(n) Space complexity: O(d) where d is the recursion depth. #DataStructures #Algorithms #LinkedList #JavaScript #DSA #CodingPractice #LeetCode #ProblemSolving #SoftwareEngineering
To view or add a comment, sign in
-
-
What does createUser("Naveen", true, false, true) even mean? 🦇 If you write functions that take multiple boolean arguments, you are suffering from Boolean Blindness. At the call site, it’s just a mystery sequence of true and false. It forces every other developer on your team to CTRL + Click to read the source code just to figure out what those flags do. Worse? It is incredibly easy to accidentally swap two booleans, and the compiler won’t warn you because the types match. 💥 The Fix: The Options Object Pattern 🛠️ Instead of passing raw booleans, pass a single configuration object. Why this is infinitely better: 1. Self-Documenting: The property names tell you exactly what the boolean does at the call site. 2. Order Doesn't Matter: You can't accidentally swap sendEmail and isVIP. 3. Extensible: If you need to add a 4th parameter later, you don't break existing function calls. Write code for the person reading it, not just the machine executing it. Do you enforce the Options Object pattern in your PRs, or do you still allow "naked" booleans? 👇 #CleanCode #TypeScript #JavaScript #SoftwareEngineering #WebDevelopment #DeveloperTips #Refactoring
To view or add a comment, sign in
-
-
📌 #61 DailyLeetCodeDose Today's problem: 146. LRU Cache – 🟡 Medium This task looks simple until you remember the O(1) requirement. A map alone is not enough – we also need to track recency. The key idea is combining a hash map with a doubly linked list: the map gives instant access, the list keeps items ordered by usage. Every get or put moves the node to the front, making it the most recently used. When capacity is exceeded, the last node is removed – that's the true LRU. Clean design, strict O(1), and a great reminder that the right data structure is often the whole solution. https://lnkd.in/epVtDYKH #DailyLeetCodeDose #LeetCode #JavaScript #Algorithms #ProblemSolving #Coding
To view or add a comment, sign in
-
-
What is the difference between Expression and Statement?Expression: produces a value. Statement: performs an action. Example: let x = 3 + 4 * 6; ---------- (i) This is one statement and contains three expressions: 4 * 6 = 24 3 + 24 = 27 x = 27 Here, the calculation happens through expressions. How the JS engine works for this equation: 1.Parsing i. Lexical analysis (tokenization) ii. AST (Abstract Syntax Tree) creation 2.Traversal – the engine goes through the AST nodes. 3.Runtime – expressions are evaluated, variables are assigned. 4.Display / Output – the final value is stored and available in memory. Expressions are very important because all calculations in JavaScript happen through them. Concepts like prefix and postfix operators also come from expressions. If you want to know details, you can see this video.
JavaScript Syntax Explained | Variables, Memory Allocation & JS Engine Workflow
https://www.youtube.com/
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