LeetCode20. 有效的括号
- 题目链接
- 代码
题目链接
https://leetcode.cn/problems/search-in-a-binary-search-tree/
代码
递归法
# 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 rootif root.val < val:result = self.searchBST(root.right, val)if root.val > val:result = self.searchBST(root.left, val)return result
迭代
class Solution:def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:while root:if root.val < val: root = root.rightelif root.val > val: root = root.leftelse: return root