题目链接
https://leetcode.cn/problems/search-in-a-binary-search-tree/
代码
递归法文章来源:https://www.toymoban.com/news/detail-680534.html
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if not root or root.val == val:
return root
if root.val < val:
result = self.searchBST(root.right, val)
if root.val > val:
result = self.searchBST(root.left, val)
return result
迭代文章来源地址https://www.toymoban.com/news/detail-680534.html
class Solution:
def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
while root:
if root.val < val: root = root.right
elif root.val > val: root = root.left
else: return root
到了这里,关于LeetCode(力扣)700. 二叉搜索树中的搜索Python的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!