700. 二叉搜索树中的搜索
image-20201130195559871
思路
首先搞清楚二叉搜索树的机制,左儿子的值都小于当前节点,右儿子的值都大于当前节点 然后就可以快速写出程序了,用递归很好实现 1. 相等直接return 2. 小于当前节点,直接去树节点的左子树寻找 3. 大于当前节点,去树节点的右子树寻找
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def searchBST(self, root: TreeNode, val: int) -> TreeNode: if root is None: return None if val == root.val: return root elif val > root.val: return self.searchBST(root.right, val) else: return self.searchBST(root.left, val)
image-20201130195817737
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func searchBST(root *TreeNode, val int) *TreeNode { if root == nil { return nil } if val < root.Val { return searchBST(root.Left, val) } if val > root.Val { return searchBST(root.Right, val) } return root }
image-202011302003410