问题: 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.node
For example,
Given the tree:
4
/ \
2 7
/ \
1 3
And the value to search: 2
复制代码
方法: 递归调用检索,惟一不一样于普通树的是二叉搜索树能够减小递归调用次数,看下二叉搜索树的定义就懂了。git
具体实现:github
class SearchInABinarySearchTree {
class TreeNode(var `val`: Int = 0) {
var left: TreeNode? = null
var right: TreeNode? = null
}
fun searchBST(root: TreeNode?, `val`: Int): TreeNode? {
if (root == null) {
return null
}
if(root.`val` == `val`) {
return root
} else if (root.`val` > `val`) {
return searchBST(root.left, `val`)
} else {
return searchBST(root.right, `val`)
}
}
}
fun main(args: Array<String>) {
}
复制代码
有问题随时沟通bash