问题描述:
思路1:层序遍历
# 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: TreeNode, val: int) -> TreeNode: from collections import deque queue=deque([root]) while queue: node=queue.popleft() if node.val==val:return node if node.left:queue.append(node.left) if node.right:queue.append(node.right)
下面利用二叉搜索树节点值大于左子树小于右子树的性质 进行优化
思路2:
# 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: TreeNode, val: int) -> TreeNode: if root.val>val and root.left:return self.searchBST(root.left,val) if root.val<val and root.right:return self.searchBST(root.right,val) if root.val==val:return root
我是小郑 期待与你一起进步😀