美文网首页
700.Search in a Binary Search Tr

700.Search in a Binary Search Tr

作者: 北京旅游 | 来源:发表于2018-08-09 20:46 被阅读0次

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,

在该二叉树中搜索'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 Tr

      本文链接:https://www.haomeiwen.com/subject/sqzcbftx.html