添加 0700.二叉搜索树中的搜索 go版本

添加 0700.二叉搜索树中的搜索 go版本
This commit is contained in:
X-shuffle
2021-06-13 22:17:57 +08:00
committed by GitHub
parent 01f87cc505
commit ac1e326cbf

View File

@ -241,6 +241,56 @@ class Solution:
Go
> 递归法
```go
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
//递归法
func searchBST(root *TreeNode, val int) *TreeNode {
if root==nil||root.Val==val{
return root
}
if root.Val>val{
return searchBST(root.Left,val)
}
return searchBST(root.Right,val)
}
```
> 迭代法
```go
/**
* 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{
break
}
}
return root
}
```