✅ Solved LeetCode: Binary Tree Postorder Traversal (145) Implemented an iterative Postorder Traversal in JavaScript using two stacks, following the sequence: Left → Right → Root. The strategy works as follows: - Use the first stack (s1) to process nodes in a modified preorder fashion (Root → Left → Right). - Push each popped node into a second stack (s2). - After traversal, pop nodes from s2 to get the correct Postorder sequence. This approach effectively simulates recursion while maintaining the correct traversal order. ⏱ Time Complexity: O(n) — each node is processed once 🧠 Space Complexity: O(n) — due to the use of two stacks A neat stack-based trick to achieve Postorder without recursion! 🌳
Binary Tree Postorder Traversal in JavaScript
More Relevant Posts
-
✅ Solved LeetCode: Binary Tree Postorder Traversal (145) Implemented an iterative Postorder Traversal in JavaScript using a single stack and a lastVisited pointer, following the sequence: Left → Right → Root. The strategy works as follows: - Traverse to the leftmost node, pushing nodes onto the stack. - Peek the top of the stack to decide the next move: -If the right child exists and hasn’t been visited, move to the right subtree. -Otherwise, process (visit) the node and mark it as last visited. - Repeat until both the stack is empty and current node is null. This approach simulates recursion explicitly while avoiding multiple stacks. ⏱ Time Complexity: O(n) — each node is visited once 🧠 Space Complexity: O(h) — stack space based on tree height A more optimized and elegant iterative way to achieve Postorder traversal! 🌳
To view or add a comment, sign in
-
-
✅ Solved LeetCode: Path Sum (112) — Alternative Approach Implemented a clean recursive (top-down) DFS solution in JavaScript using a subtractive strategy. Approach: - If the node is null, return false. - If the node is a leaf node, simply check: - root.val === targetSum - Otherwise: - Recursively call the function on left and right subtrees. - Pass targetSum - root.val to reduce the remaining required sum. - Return leftResult || rightResult. This approach eliminates the need for an external variable and keeps the recursion concise and expressive. Time Complexity: O(n) — each node is visited once Space Complexity: O(h) — recursion stack space (where h is tree height) A clean divide-and-conquer way to solve Path Sum efficiently! 🌳
To view or add a comment, sign in
-
-
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
-
-
✅ 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!
To view or add a comment, sign in
-
-
🚀 Optimizing Array Manipulation: The Two-Pointer Strategy 💡 Yesterday, I tackled the "Move Zeroes" challenge on LeetCode using JavaScript! 👨💻 The mission? Move all 0s to the end of an array while preserving the relative order of non-zero elements—all without creating a copy of the array. 🚫📋 Initially, a common approach is to filter and join arrays, but that results in $O(n)$ space complexity. To keep the solution professional and memory-efficient, I implemented the Two-Pointer technique. 🎯 🧠 The Logic: Pointer A (Slow): 🐢 Tracks the position where the next non-zero element belongs. Pointer B (Fast): 🐇 Iterates through the entire array to find non-zero values. The Swap: ✨ Whenever Pointer B encounters a non-zero element, we swap the values and increment Pointer A. 📊 The Result: ✅ Time Complexity: $O(n)$ (Clean, single-pass efficiency) ✅ Space Complexity: $O(1)$ (Optimized in-place manipulation) Mastering these "in-place" constraints is a game-changer for writing scalable, production-ready code. It’s not just about solving the problem; it’s about solving it efficiently. 💪 #JavaScript #WebDevelopment #LeetCode #Algorithms #CodingInterview #SoftwareEngineering #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
-
✅ Solved LeetCode: Invert Binary Tree (226) — Recursive DFS Approach Implemented a clean recursive solution in JavaScript using a simple swap-and-recurse strategy. Approach: - If the node is null, return it immediately. - Swap the left and right children: - Store root.left in a temporary variable. - Assign root.right to root.left. - Assign the temporary value to root.right. - Recursively call the function on: - root.left - root.right - Return the root after inversion. This approach flips the tree at every node and naturally propagates the inversion down to all subtrees using recursion. Time Complexity: O(n) — each node is visited once Space Complexity: O(h) — recursion stack space (where h is tree height) A classic tree problem solved with a simple and elegant recursive swap!
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
-
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
-
-
The fastest JS code I wrote this year… wasn’t JavaScript. Today I published the deeper story. It starts with a simple problem: pure JavaScript was becoming the bottleneck for large image comparisons. I experimented with multiple approaches and benchmarks and eventually ported the core algorithm to Rust. Along the way, I looked at existing tools like odiff. It's very fast, but typically used through spawned processes or long-running helpers to avoid that overhead. The interesting part for me was the interface layer. Instead of spawning binaries or running a server, the library uses N-API to let Node call the Rust implementation directly. That removes the process overhead and makes batch diffing much cheaper. If you like performance deep dives, the full write-up is here: https://lnkd.in/dDP58i6q Also, thanks to HackerNoon for selecting it as a Top Story.
To view or add a comment, sign in
-
I tried implementing the internal working of forEach and map to better understand how they operate under the hood. Both are higher order functions because they accept another function as an argument. Internally, they iterate over the array (typically via a loop) and execute the callback for each element. forEach : Iterates through the array. Executes the provided callback on each element. Does not return a new array (returns undefined). Primarily used for logging map : Iterates through the array. Executes the callback on each element. Stores the callback’s return value in a new array. Returns the new transformed array. Does not mutate the original array. Rewriting these methods manually with a for loop really clarifies their behavioral difference : forEach is about execution, map is about transformation. #JavaScript #WebDevelopment #FunctionalProgramming #LearnInPublic #ChaiAurCode
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