题目链接:https://leetcode-cn.com/problems/search-in-a-binary-search-tree/
执行用时:160 ms, 在所有 Swift 提交中击败了96.36%的用户
内存消耗:14.4 MB, 在所有 Swift 提交中击败了14.54%的用户
迭代
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| class Solution { func searchBST(_ root: TreeNode?, _ val: Int) -> TreeNode? { var root = root while let node = root{ if node.val < val { root = node.right }else if node.val > val { root = node.left }else{ return node } } return nil } }
|
递归
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| class Solution { func searchBST(_ root: TreeNode?, _ val: Int) -> TreeNode? { if root == nil { return root } if root?.val == val { return root }else if root!.val > val { return searchBST(root?.left, val) }else { return searchBST(root?.right, val) } } }
|