1 """ 2 Given the root node of a binary search tree (BST) and a value. You need to find the node in the BST that the node's value equals the given value. Return the subtree rooted with that node. If such node doesn't exist, you should return NULL. 3 For example, 4 Given the tree: 5 4 6 / 7 2 7 8 / 9 1 3 10 And the value to search: 2 11 You should return this subtree: 12 2 13 / 14 1 3 15 """ 16 """ 17 两种方法 18 解法一:我用了一个p指针来存结果,进行二叉树的查找 19 """ 20 class TreeNode: 21 def __init__(self, x): 22 self.val = x 23 self.left = None 24 self.right = None 25 26 class Solution1: 27 def searchBST(self, root, val): 28 p = root 29 while p: 30 if p.val == val: 31 return p 32 elif p.val > val: 33 p = p.left 34 else: 35 p = p.right 36 return None 37 """ 38 解法二:递归,找到相等的返回 39 """ 40 class Solution2: 41 def searchBST(self, root, val): 42 if not root: 43 return None 44 if root.val == val: 45 return root 46 elif root.val > val: 47 return self.searchBST(root.left, val) 48 else: 49 return self.searchBST(root.right, val)