Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit a752096

Browse files
700. Search in a Binary Search Tree
1 parent e6a7110 commit a752096

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

‎Trees/searchBST.py‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# You are given the root of a binary search tree (BST) and an integer val.
2+
# Find the node in the BST that the node's value equals val and return the subtree
3+
# rooted with that node. If such a node does not exist, return null.
4+
5+
6+
# Example 1:
7+
# Input: root = [4,2,7,1,3], val = 2
8+
# Output: [2,1,3]
9+
10+
# Example 2:
11+
# Input: root = [4,2,7,1,3], val = 5
12+
# Output: []
13+
14+
15+
# Constraints:
16+
17+
# The number of nodes in the tree is in the range [1, 5000].
18+
# 1 <= Node.val <= 107
19+
# root is a binary search tree.
20+
# 1 <= val <= 107
21+
22+
23+
from typing import Optional
24+
25+
# Definition for a binary tree node.
26+
class TreeNode:
27+
def __init__(self, val=0, left=None, right=None):
28+
self.val = val
29+
self.left = left
30+
self.right = right
31+
class Solution:
32+
def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
33+
if not root:
34+
return None
35+
if root.val == val:
36+
return root
37+
if root.val < val:
38+
return self.searchBST(root.right, val)
39+
else:
40+
return self.searchBST(root.left, val)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /