🚀Day 113 of #LeetCode Challenge! Problem: Search in a Binary Search Tree 🌳 My Approach: Since this is a Binary Search Tree (BST), we can use the BST property: If the value we are searching is less than the current node’s value → search in the left subtree. If it is greater → search in the right subtree. Continue until we either find the node or reach a NULL pointer. ✨ Example: Input: root = [4,2,7,1,3], val = 2 Output: [2,1,3] Explanation: The subtree rooted at value 2 is returned. ⏱ Time Complexity: O(h) — where h is the height of the tree 📦 Space Complexity: O(h) — recursive call stack 📌 Key Insight: BST property helps us efficiently go left or right — no need to search the entire tree! 👨💻 GitHub Link: https://lnkd.in/gz6UmG6y #LeetCode #BinarySearchTree #TreeTraversal #Recursion #ProblemSolving #DSA #CodingChallenge #C++ #Day113
Search in a Binary Search Tree using BST property
More Relevant Posts
-
🚀 Day 123 of #LeetCode Challenge! Problem: Convert Sorted Array to Binary Search Tree 💡 My Approach: The task is to convert a sorted array into a height-balanced BST — meaning the depth of the two subtrees of every node should not differ by more than one. Here’s how I approached it: Pick the middle element of the array as the root (ensures balance). Recursively build the left subtree from the left half. Recursively build the right subtree from the right half. This method ensures the tree is balanced and follows the BST property (left < root < right). 🧠 Key Idea The midpoint of the current range always becomes the root, making the BST height-balanced naturally. ✨ Example Input: nums = [-10, -3, 0, 5, 9] Output: A balanced BST like: 0 / \ -3 9 / / -10 5 ⏱ Complexity TypeValueTimeO(N) — each element is processed onceSpaceO(log N) — recursion stack (for balanced BST) 📎 GitHub Link: https://lnkd.in/gDkzKT6A #LeetCode #BinarySearchTree #Recursion #C++ #ProblemSolving #DSA #Day123 #CodingChallenge
To view or add a comment, sign in
-
-
🚀 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 128 of #LeetCode Challenge! Problem: Trim a Binary Search Tree 💡 My Approach: The goal is to trim the BST so that all its values lie within the range [low, high] while still preserving the structure of a valid BST. Since this is a BST, we can take advantage of its ordering property: If root->val < low, the entire left subtree is out of range → return the right subtree. If root->val > high, the entire right subtree is out of range → return the left subtree. Otherwise, recursively fix both children. ✨ Key Idea The BST property lets us skip entire subtrees efficiently, making the solution clean and optimal. ⏱ Complexity TypeValueTimeO(N) — every node is visited onceSpaceO(H) — recursion stack (H = height of the tree) 📎 GitHub Link: https://lnkd.in/gfYMNbGk #LeetCode #BST #BinarySearchTree #TrimBST #DSA #C++ #CodingChallenge #Day128
To view or add a comment, sign in
-
-
🚀 Day 112 of #LeetCode Challenge! Problem: Diameter of Binary Tree 💡 My Approach: The diameter of a binary tree is the longest path between any two nodes (may or may not pass through the root). The trick is to calculate the height of each subtree while keeping track of the maximum left + right path encountered. Use a helper function height() that: Recursively computes left and right subtree heights. Updates the global diameter as the maximum sum of left and right heights. ✨ Example: Input: [1,2,3,4,5] Output: 3 Explanation: The longest path is [4,2,1,3] or [5,2,1,3] ⏱ Time Complexity: O(N) — visit every node once 💾 Space Complexity: O(H) — recursive stack (H = height of tree) 🌱 Key Insight: At each node, the longest path through it is leftHeight + rightHeight. The overall diameter is the maximum of all such paths. 👨💻 GitHub Link: https://lnkd.in/dvUDMZUC #LeetCode #BinaryTree #Recursion #TreeTraversal #DSA #CodingChallenge #C++ #Day112
To view or add a comment, sign in
-
-
Day 11 of 30 Solving Leetcode ✅ Problem : Minimum Array Changes to Make Differences Equal - O(n*logn) Approach : Binary Search Find the maximum difference we can get abs(nums[i]-nums[n-i-1]) using one operation and store it in sorted array . Because we can make difference equal to x , then we can also make difference x-1 . So This will be monotonic & use for binary search . And we can make any difference <=k using 2 operations . For every difference equal to 0 to k , Try to make every difference using binary search . If we at diff = j , then in one operation = n/2 - lower_bound of j in arr . in zero operation , we can find initially whose diff equal to j , and rest will take 2 operation . and take minimum of all diff from 0 to k . #leetcode #dsa #problemsolving #leetcodechallenge
To view or add a comment, sign in
-
-
Day 59 of the #90DaysWithDSA challenge is complete! Today tackled a fascinating problem where a BST had two nodes swapped, and the mission was to identify and recover the original structure. Today's Problem: Recover Binary Search Tree (LeetCode 99 - Medium) The challenge: You are given the root of a BST where exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure. The key insight is that an in-order traversal of a BST should produce a sorted sequence. When two nodes are swapped, this creates specific violations in the sorted order: The Approach: Perform in-order traversal to identify the two nodes that are out of order Look for the first occurrence where current node value < previous node value (the first swapped node) Look for the last occurrence where current node value < previous node value (the second swapped node) Swap the values of these two identified nodes This runs in O(n) time with O(h) space, efficiently fixing the tree in a single pass. Key Takeaway: In-order traversal is not just for outputting sorted values - it's a powerful debugging tool for verifying and fixing BST properties. This pattern is essential for tree validation and correction algorithms used in database indexing and file systems. 59 days of consistent coding. The ability to diagnose and fix structural issues in trees is growing! 🔧 Let's keep debugging and recovering together! 👉 Want to master tree validation and correction algorithms? JOIN THE JOURNEY! Comment "Recovering with you!" below and share what tree debugging problem you're solving. 👉 Repost this ♻️ to help other developers discover this challenge and enhance their tree algorithm skills. What's the most interesting tree corruption or recovery problem you've encountered? #Day59 #BinarySearchTree #BST #InOrderTraversal #TreeRecovery #CodingInterview #Programming #SoftwareEngineering #Tech #LearnInPublic #Developer #LeetCode #ProblemSolving
To view or add a comment, sign in
-
-
Day 56 of the #90DaysWithDSA challenge is complete! Today was about ensuring a binary tree follows the fundamental properties of a Binary Search Tree (BST). Today's Problem: Validate Binary Search Tree (LeetCode 98 - Medium) The challenge: Given the root of a binary tree, determine if it is a valid BST where: The left subtree of a node contains only nodes with keys less than the node's key The right subtree of a node contains only nodes with keys greater than the node's key Both left and right subtrees must also be BSTs The key insight is that an in-order traversal of a BST should yield values in strictly increasing order. This leads to an elegant solution: The Approach: Perform in-order traversal (left, root, right) Keep track of the previously visited node's value At each node, ensure the current value is greater than the previous value If any node violates this condition, the tree is not a valid BST This runs in O(n) time with O(h) space for the recursion stack. Key Takeaway: Many BST validation problems can be solved by leveraging the sorted property that emerges from in-order traversal. This pattern is fundamental for BST problems and demonstrates how tree traversal order can reveal structural properties. 56 days of consistent coding. The BST properties and traversal techniques are becoming deeply ingrained! 🚀 Let's keep validating our tree knowledge together! 👉 Want to master BST properties and validation techniques? JOIN THE QUEST! Comment "Validating with you!" below and share what BST problem you're solving today. 👉 Repost this ♻️ to help other developers discover this challenge and strengthen their tree algorithm skills. What's the most interesting BST property you've utilized in solving problems? #Day56 #BinarySearchTree #BST #InOrderTraversal #TreeValidation #CodingInterview #Programming #SoftwareEngineering #Tech #LearnInPublic #Developer #LeetCode #ProblemSolving
To view or add a comment, sign in
-
-
✨ LeetCode 450 – Delete Node in a BST Today I solved an interesting Binary Search Tree problem. 🧩 Problem Summary: We are given a BST and a key. We need to delete the node with that key while ensuring the BST property remains intact. The challenge comes when the node has two children, where we replace it with its inorder successor. 💡 Key Idea: If the node has 0 or 1 child, just replace it directly. If it has 2 children, find the minimum value in the right subtree (inorder successor) and replace the node with it, then delete that successor. 📌 Core Operations Used: Binary Search Tree traversal Inorder successor logic Recursion for subtree restructuring This was a really good practice problem to strengthen my understanding of BST manipulation and tree recursion patterns. #LeetCode #DSA #BinarySearchTree #Java #CodingJourney #100DaysOfCode 🚀
To view or add a comment, sign in
-
-
🌟 Day 117 of 150 – Find Peak Element [LeetCode 162] 🌟 🔧 Problem Brief: You are given an integer array nums[], where a peak element is one that is strictly greater than its neighbors. Your task → Return the index of any peak element. You may assume that elements outside the array are -∞, i.e., nums[-1] = nums[n] = -∞. 🎯 Goal: Find any peak element using a binary search approach in O(log n) time ⏱. 🧠 How We Solve It? → Binary Search on Slopes 1️⃣ Initialize two pointers: left = 0, right = nums.length - 1 2️⃣ While left < right: Compute middle index → mid = (left + right) / 2 Compare middle element with its next neighbor: If nums[mid] > nums[mid + 1] → we are on a descending slope, so move left → right = mid Else → we are on an ascending slope, so move right → left = mid + 1 3️⃣ When the loop ends, left == right — this index is guaranteed to be a peak. 🧩 Example Walkthrough 📥 Input: nums = [1, 2, 3, 1] 📘 Steps: Start: left = 0, right = 3 mid = 1 → nums[mid]=2, nums[mid+1]=3 → ascending → left = 2 mid = 2 → nums[mid]=3, nums[mid+1]=1 → descending → right = 2 ✅ Output: 2 (index of peak element 3) 🧮 Complexity Analysis ⏱ Time Complexity: O(log n) 💾 Space Complexity: O(1) 📎 GitHub Link: https://lnkd.in/e5kCCFJY #Day117 #LeetCode #FindPeakElement #BinarySearch #JavaDSA #ProblemSolving #CodingChallenge #InterviewPrep #TechWithSaravana #150DaysOfCode #DSA #LearningJourney #CodeEveryday #Algorithm
To view or add a comment, sign in
-
🎯 LeetCode 700 – Search in a Binary Search Tree Today I spent some time revisiting the fundamentals of Binary Search Trees (BSTs) and solved LeetCode Problem 700. Even though this is considered an easy problem, I really like how it reinforces the core intuition behind BSTs. 🧩 Problem Insight: We are given the root of a Binary Search Tree and a value. The task is to find and return the node that contains this value. If the value doesn’t exist in the tree, we return null. What makes this problem interesting is not the complexity, but how naturally the BST structure guides the search process. 💡 Key Idea: In a Binary Search Tree, for any node: Left subtree values are smaller Right subtree values are greater This ordering means instead of searching the entire tree, we can decide the direction at each step: If the value we are searching for is smaller than the current node → move left If it’s greater → move right If it matches → we found it This makes the search efficient and elegant. The tree basically tells you where to go next. ⏱ Time Complexity: O(h) where h is the height of the tree (Best case: balanced tree. Worst case: skewed tree.)
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