LC700. 二叉搜索树中的搜索
解题思路
其实只要知道了二叉搜索树(binary search tree)的性质就会解这道题啦,剩下都是敲代码
- 若它的左子树不为空,则左子树上所有节点的值均小于它根节点的值
- 若它的右子树不为空,则右子树上所有节点的值均小于它根节点的值
- 它的左、右子树也分别为二叉搜索树
代码
Go
递归
1 | /** |
迭代
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func searchBST(root *TreeNode, val int) *TreeNode {
for root != nil{
if root.Val > val {
root = root.Left
} else if root.Val < val {
root = root.Right
} else {
return root
}
}
return root
}
评论
