🚀 Day 125 of #LeetCode Challenge! Problem: Binary Tree Preorder Traversal 💡 My Approach: The goal is to perform a preorder traversal of a binary tree — visiting nodes in the order: Root → Left → Right Here’s the step-by-step logic: Start from the root node. Visit (record) the root value first. Recursively traverse the left subtree, then the right subtree. Store values in a vector as you go. ✨ Example Input: [1, null, 2, 3] Output: [1, 2, 3] 🧠 Key Idea Preorder traversal is useful when you need to copy or serialize a tree — it captures the structure starting from the root. ⏱ Complexity TypeValueTimeO(N) — each node visited onceSpaceO(H) — recursion stack (H = height of tree) 📎 GitHub Link: https://lnkd.in/gZ6GeXzm #LeetCode #BinaryTree #PreorderTraversal #Recursion #DSA #C++ #ProblemSolving #CodingChallenge #Day125
How to perform a preorder traversal of a binary tree using recursion and C++.
More Relevant Posts
-
🚀 Day 124 of #LeetCode Challenge! Problem: Binary Tree Inorder Traversal 💡 My Approach: The goal is to perform an inorder traversal of a binary tree — visiting nodes in the order: Left → Root → Right. Here’s how I implemented it: Use recursion to traverse the tree. Start from the root node. Recursively visit the left subtree, then record the root value, and finally traverse the right subtree. This ensures all nodes are visited in sorted order for a BST. ✨ Example Input: [1, null, 2, 3] Output: [1, 3, 2] 🧠 Key Idea Inorder traversal naturally retrieves nodes in ascending order if the tree is a Binary Search Tree (BST). ⏱ Complexity TypeValueTimeO(N) — each node visited onceSpaceO(H) — recursion stack (H = height of tree) 📎 GitHub Link: https://lnkd.in/gBgJShhT #LeetCode #BinaryTree #InorderTraversal #Recursion #DSA #C++ #ProblemSolving #CodingChallenge #Day124
To view or add a comment, sign in
-
-
🚀 Day 115 of #LeetCode Challenge! Problem: Symmetric Tree 🌳 Concept: Check whether a binary tree is a mirror of itself (i.e., symmetric around its center). 💡 My Approach: Use recursion to compare left and right subtrees. A tree is symmetric if: Left subtree of left node matches right subtree of right node Right subtree of left node matches left subtree of right node Base cases: Both nodes NULL → symmetric ✅ One NULL and one not → not symmetric ❌ Values must match ✨ Example: Input: [1,2,2,3,4,4,3] Output: true ⏱ Time Complexity: O(N) — visiting all nodes 📦 Space Complexity: O(H) — recursion stack (H = height of tree) 📌 Key Insight: This is a classic mirror check — left's left must mirror right's right! 👨💻 GitHub Link: https://lnkd.in/gid6xjvn #LeetCode #BinaryTree #Recursion #SymmetricTree #MirrorTree #DSA #ProblemSolving #C++ #CodingChallenge #Day114
To view or add a comment, sign in
-
-
🚀 Day 117 of #LeetCode Challenge! Problem: Univalued Binary Tree 💡 My Approach: We need to check if all nodes in the binary tree have the same value. 🔍 Steps: Store the root value as the target value DFS through every node If any node's value ≠ root value → return false If traversal completes with no mismatch → return true ✅ 📌 Key Idea: A binary tree is univalued if every node contains the same value. ✨ Example: Input: [1,1,1,1,1,null,1] Output: true Input: [2,2,2,5,2] Output: false ⏱ Time Complexity: O(N) — every node is checked 💾 Space Complexity: O(H) — recursion stack (H = tree height) 👨💻 GitHub Link: https://lnkd.in/g3xFQpAm #LeetCode #BinaryTree #DFS #Recursion #DSA #Day117 #C++ #ProblemSolving #CodingChallenge
To view or add a comment, sign in
-
-
🚀 Day 127 of #LeetCode Challenge! Problem: Binary Tree Level Order Traversal 💡 My Approach: This problem involves traversing the binary tree level by level — also known as Breadth-First Search (BFS) traversal. Here’s the step-by-step breakdown: Use a queue to store nodes level by level. For each level, store all node values in a temporary list. Push their left and right children into the queue. After finishing one level, add it to the result vector. ✨ Example Input: [3,9,20,null,null,15,7] Output: [[3], [9,20], [15,7]] 🧠 Key Idea This traversal captures the hierarchical structure of the tree perfectly — often used in problems involving level-based processing, like Zigzag traversal or average of levels. ⏱ Complexity TypeValueTimeO(N) — each node visited onceSpaceO(N) — for queue and result storage 📎 GitHub Link: https://lnkd.in/gntMrKbU #LeetCode #BinaryTree #BFS #LevelOrderTraversal #DSA #ProblemSolving #C++ #CodingChallenge #100DaysOfCode #Day127
To view or add a comment, sign in
-
-
🚀 Day 114 of #LeetCode Challenge! Problem: Symmetric Tree 🌳 Concept: Check whether a binary tree is a mirror of itself (i.e., symmetric around its center). 💡 My Approach: Use recursion to compare left and right subtrees. A tree is symmetric if: Left subtree of left node matches right subtree of right node Right subtree of left node matches left subtree of right node Base cases: Both nodes NULL → symmetric ✅ One NULL and one not → not symmetric ❌ Values must match ✨ Example: Input: [1,2,2,3,4,4,3] Output: true ⏱ Time Complexity: O(N) — visiting all nodes 📦 Space Complexity: O(H) — recursion stack (H = height of tree) 📌 Key Insight: This is a classic mirror check — left's left must mirror right's right! 👨💻 GitHub Link: https://lnkd.in/grXFRA2i #LeetCode #BinaryTree #Recursion #SymmetricTree #MirrorTree #DSA #ProblemSolving #C++ #CodingChallenge #Day114
To view or add a comment, sign in
-
-
🔥 HyperRevision with Structure – Day 87 🔥 🧩 Problem solved today: 1️⃣ Surrounded Regions (LeetCode 130) 💭 Thoughts: Back to Neetcode 150. At first glance, this problem looks just like Number of Islands, but there’s a subtle twist — you need an extra boundary check before marking 'O's as 'X'. The key idea is to start DFS from the border 'O's so that only the inner, fully-surrounded regions are flipped. ⏱️ Time Complexity: O(m × n) 💾 Space Complexity: O(m × n) (due to recursion stack) 📌 GitHub link in comments #HyperRevision #LeetCode #DFS #GraphTraversal #NeetCode150
To view or add a comment, sign in
-
-
🚀 Day 122 of #LeetCode Challenge! Problem: Subtree of Another Tree 💡 My Approach: The goal is to check whether one tree (subRoot) is a subtree of another (root). Here’s how I approached it: Traverse the main tree (root) recursively. At each node, check if the subtree starting there is identical to subRoot. If not, keep checking in the left and right subtrees. For the comparison, a helper function isSameTree() ensures both trees have identical structure and node values. 🧠 Key Idea A tree subRoot is a subtree of root if there exists a node in root such that the subtree rooted at that node is structurally identical to subRoot. ✨ Example Input: root = [3,4,5,1,2] subRoot = [4,1,2] Output: ✅ true Explanation: The subtree starting at node 4 in root matches subRoot. ⏱ Complexity TypeValueTimeO(M × N) — for each node in root, we may compare with all nodes in subRootSpaceO(H) — recursion stack (H = height of the tree) 📎 GitHub Link: https://lnkd.in/gv3w8RFe #LeetCode #BinaryTree #Recursion #C++ #ProblemSolving #Day122 #CodingChallenge
To view or add a comment, sign in
-
-
💻 Day 47 of #50DaysOfLeetCode Challenge 🚀 Problem: Binary Tree Maximum Path Sum (Leetcode 124) The goal was to find the maximum path sum in a binary tree — where the path can start and end at any node, not just the root. 🌲 🧠 Approach: I solved it using postorder traversal (Left → Right → Root). At every node, I calculated: 1️⃣ bothpaths → path passing through root (left + right + root) 2️⃣ bestpath → best path going downward from root (max of left or right + root) 3️⃣ onlyroot → when only the root node is part of the path At each step, I updated a global maxsum with the best of these three values. This way, every node contributed the maximum possible sum considering all cases. 🧩 Key Takeaway: 👉 Always think in terms of "What value should I return to parent?" vs "What value should I update globally?" 👉 Binary tree recursion becomes intuitive once you separate these two thoughts.
To view or add a comment, sign in
-
-
Day 22 of #100DaysOfCode Today I solved the “Permutation in String” problem on LeetCode — a tricky one that really sharpens your understanding of sliding window and frequency mapping in strings. 🧩 Problem in short: Given two strings s1 and s2, the task is to check if any permutation of s1 exists as a substring in s2. At first glance, it feels like a brute-force problem — generate all permutations of s1 and check each in s2. But that’s computational suicide for longer strings. So the challenge was to find a smarter, optimized approach. ⚙️ Intuitive Approach: Instead of generating permutations, I focused on character frequencies. Maintain two frequency arrays — one for s1 and one for the current window of s2. Slide the window across s2, adding and removing characters as you move. Whenever both frequency arrays match, it means that substring of s2 is a permutation of s1. This approach reduces the complexity drastically and relies on pattern recognition through frequency matching, not brute force. Every day in this challenge is a reminder that optimization isn’t about doing less work — it’s about doing the right work. #LeetCode #C++ #ProblemSolving #DSA #CodingJourney #100DaysOfCode
To view or add a comment, sign in
-
-
🔍 Day 30 | Shift Happens (and That’s Beautiful) Today’s LeetCode challenge was #848 – Shifting Letters 🌀 At first glance, it looks like a simple “shift characters” task — but under the hood, it’s a neat example of prefix-sum logic meets modular arithmetic. 💡 The Problem: For each index i, shift the first i+1 letters by shifts[i] times — wrapping around from 'z' to 'a'. 🧠 The Trick: If we start from the end of the string and move backward, we can keep a cumulative shift sum that already accounts for all later shifts. This avoids repeatedly looping over the prefix and keeps our time complexity O(n) instead of O(n²). ⚙️ Approach: Traverse from right to left Keep adding each shift to a running total (totalShift) Apply totalShift % 26 to shift the current character efficiently Update the string using a StringBuilder 💨 Why It’s Optimal: ✅ Single pass — linear time ✅ Constant extra space ✅ Clean and scalable even for large inputs (up to 10⁵ length! Sometimes the cleanest solutions come from flipping your perspective — literally shifting your direction Shishir chaurasiya and PrepInsta #LeetCode #CodingChallenge #Java #Algorithms #ProblemSolving #LearningEveryday
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