Skip to content

Commit de95d89

Browse files
VanshVansh
Vansh
authored and
Vansh
committed
added lc 700
1 parent 7f760a7 commit de95d89

File tree

3 files changed

+260
-0
lines changed

3 files changed

+260
-0
lines changed
Lines changed: 260 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,260 @@
1+
---
2+
id: search-in-a-binary-search-tree
3+
title: Search in a Binary Search Tree
4+
sidebar_label: 700. Search in a Binary Search Tree
5+
6+
tags:
7+
- Binary Tree
8+
- BST
9+
- Search
10+
11+
description: "This is a solution to the Search in a Binary Search Tree problem on LeetCode."
12+
---
13+
14+
## Problem Description
15+
You are given the `root` of a binary search tree (BST) and an integer `val`.
16+
Find the node in the BST that the node's value equals `val` and return the subtree rooted with that node. If such a node does not exist, return `null`.
17+
### Examples
18+
19+
**Example 1:**
20+
21+
![Example1](image.png)
22+
```
23+
Input: root = [4,2,7,1,3], val = 2
24+
Output: [2,1,3]
25+
```
26+
27+
**Example 2:**
28+
29+
![Example2](image-1.png)
30+
```
31+
Input: root = [4,2,7,1,3], val = 5
32+
Output: []
33+
34+
```
35+
36+
37+
### Constraints
38+
- The number of nodes in the tree is in the range `[1, 5000]`.
39+
- `1 <= Node.val <= 10^7`
40+
- `root` is a binary search tree.
41+
- `1 <= val <= 10^7`
42+
43+
44+
45+
## Solution for Search in a Binary Search Tree
46+
### Approach
47+
#### Brute Force
48+
- **Traverse the Tree**: Perform a level-order or in-order traversal of the tree.
49+
- **Compare Values**: At each node, compare its value with the given value `val`.
50+
- **Return Subtree**: If the node’s value equals `val`, return the subtree rooted at that node.
51+
- **Return Null**: If the traversal completes without finding the node, return `null`.
52+
53+
**Implementation:**
54+
```python
55+
class TreeNode:
56+
def __init__(self, val=0, left=None, right=None):
57+
self.val = val
58+
self.left = left
59+
self.right = right
60+
61+
def findNode(root, val):
62+
if root is None:
63+
return None
64+
65+
queue = [root]
66+
while queue:
67+
node = queue.pop(0)
68+
if node.val == val:
69+
return node
70+
if node.left:
71+
queue.append(node.left)
72+
if node.right:
73+
queue.append(node.right)
74+
75+
return None
76+
77+
# Example usage
78+
root = TreeNode(4, TreeNode(2, TreeNode(1), TreeNode(3)), TreeNode(7))
79+
val = 2
80+
subtree = findNode(root, val)
81+
print(subtree.val if subtree else "Node not found")
82+
```
83+
84+
**Complexity:**
85+
- Time Complexity: `O(n)` - We might have to visit every node in the tree.
86+
- Space Complexity: `O(n)` - In the worst case, the queue can hold all nodes in the tree (for level-order traversal).
87+
88+
**Corner Cases:**
89+
- Empty tree: Should return `null`.
90+
- Value not found: Should return `null`.
91+
92+
#### Optimized Approach
93+
- **Leverage BST Properties**: Use the properties of the BST (left subtree contains nodes with values less than the root, and the right subtree contains nodes with values greater than the root).
94+
- **Binary Search**: Traverse the tree using a binary search-like approach:
95+
- If `val` is less than the current node’s value, move to the left child.
96+
- If `val` is greater than the current node’s value, move to the right child.
97+
- If `val` equals the current node’s value, return the current node.
98+
- **Return Null**: If a leaf node is reached without finding the value, return `null`.
99+
100+
**Implementation:**
101+
102+
```python
103+
class TreeNode:
104+
def __init__(self, val=0, left=None, right=None):
105+
self.val = val
106+
self.left = left
107+
self.right = right
108+
109+
def findNode(root, val):
110+
current = root
111+
while current:
112+
if current.val == val:
113+
return current
114+
elif val < current.val:
115+
current = current.left
116+
else:
117+
current = current.right
118+
return None
119+
120+
# Example usage
121+
root = TreeNode(4, TreeNode(2, TreeNode(1), TreeNode(3)), TreeNode(7))
122+
val = 2
123+
subtree = findNode(root, val)
124+
print(subtree.val if subtree else "Node not found")
125+
```
126+
127+
**Complexity:**
128+
- Time Complexity: `O(h)`- `h` is the height of the tree. In the worst case, it can be O(n) for a skewed tree, but in a balanced tree, it is O(log n).
129+
- Space Complexity: `O(1)`- We are not using any extra space except for the input and output.
130+
131+
**Corner Cases:**
132+
- Empty tree: Should return `null`.
133+
- Value not found: Should return `null`.
134+
- Single node tree: If the single node does not match `val`, should return `null`.
135+
136+
137+
## Code in Different Languages
138+
139+
<Tabs>
140+
141+
<TabItem value="JavaScript" label="JavaScript">
142+
<SolutionAuthor name="@vansh-codes" />
143+
144+
```javascript
145+
var searchBST = function(root, val) {
146+
if (root === null) {
147+
return null;
148+
} else {
149+
if (root.val === val) {
150+
return root;
151+
} else if (root.val < val) {
152+
return searchBST(root.right, val);
153+
} else {
154+
return searchBST(root.left, val);
155+
}
156+
}
157+
};
158+
```
159+
160+
</TabItem>
161+
162+
<TabItem value="TypeScript" label="TypeScript">
163+
<SolutionAuthor name="@vansh-codes" />
164+
165+
```typescript
166+
function searchBST(root: TreeNode | null, val: number): TreeNode | null {
167+
if (root === null) {
168+
return null;
169+
} else {
170+
if (root.val === val) {
171+
return root;
172+
} else if (root.val < val) {
173+
return searchBST(root.right, val);
174+
} else {
175+
return searchBST(root.left, val);
176+
}
177+
}
178+
}
179+
```
180+
181+
</TabItem>
182+
183+
<TabItem value="Python" label="Python">
184+
<SolutionAuthor name="@vansh-codes" />
185+
186+
```python
187+
188+
class Solution(object):
189+
def searchBST(self, root, val):
190+
if root is None:
191+
return None
192+
else:
193+
if root.val == val:
194+
return root
195+
elif root.val < val:
196+
return self.searchBST(root.right, val)
197+
else:
198+
return self.searchBST(root.left, val)
199+
```
200+
201+
</TabItem>
202+
203+
<TabItem value="Java" label="Java">
204+
<SolutionAuthor name="@vansh-codes" />
205+
206+
```java
207+
import java.util.Arrays;
208+
209+
class Solution {
210+
public TreeNode searchBST(TreeNode root, int val) {
211+
if (root == null) {
212+
return null;
213+
} else {
214+
if (root.val == val) {
215+
return root;
216+
} else if (root.val < val) {
217+
return searchBST(root.right, val);
218+
} else {
219+
return searchBST(root.left, val);
220+
}
221+
}
222+
}
223+
}
224+
```
225+
226+
</TabItem>
227+
228+
<TabItem value="C++" label="C++">
229+
<SolutionAuthor name="@vansh-codes" />
230+
231+
```cpp
232+
class Solution {
233+
public:
234+
TreeNode* searchBST(TreeNode* root, int val) {
235+
if(root==NULL){
236+
return NULL;
237+
}
238+
else{
239+
if(root->val == val){
240+
return root;
241+
}else if(root->val < val){
242+
return searchBST(root->right,val);
243+
}else{
244+
return searchBST(root->left,val);
245+
}
246+
return NULL;
247+
}
248+
return NULL;
249+
}
250+
};
251+
```
252+
253+
</TabItem>
254+
</Tabs>
255+
256+
## References
257+
258+
- **LeetCode Problem**: [Search in a Binary Search Tree](https://leetcode.com/problems/search-in-a-binary-search-tree/description)
259+
260+
- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/search-in-a-binary-search-tree/solutions)
42.7 KB
Loading
59.4 KB
Loading

0 commit comments

Comments
 (0)