Search in a Binary Search Tree
Solution
class Solution {
func searchBST(_ root: TreeNode?, _ val: Int) -> TreeNode? {
if let root = root {
if root.val == val {
return root
} else {
if let left = root.left, let result = searchBST(left, val) {
return result
}
if let right = root.right, let result = searchBST(right, val) {
return result
}
return nil
}
} else {
return nil
}
}
}
解题思路
普通遍历树,找到就返回





网友评论