700.Search in a Binary Search Tree 二叉树搜索问题

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.
For example,

700.Search in a Binary Search Tree 二叉树搜索问题_第1张图片
在该二叉树中搜索'2'

You should return this subtree:
应该得到的子树

思考:二叉搜索树,特点是根节点大于他的所有左子节点,小于所以右左子节点, 所以当val < root.value时,目标节点一定在根节点的左边,大于同理二叉树这种结果,树和子树间的数据结构一样,所以非常适合递归搜索。

解法:

class Solution {
     func searchBST(_ root: TreeNode?, _ val: Int) -> TreeNode? {
        if root == nil {
            return nil
        }
        if root!.val == val {
            return root
        }
        if root!.val > val {
            return self.searchBST(root?.left, val)
        } else {
            return self.searchBST(root?.right, val)
        }
    }
}

你可能感兴趣的:(700.Search in a Binary Search Tree 二叉树搜索问题)