mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
添加 0700.二叉搜索树中的搜索 go版本
添加 0700.二叉搜索树中的搜索 go版本
This commit is contained in:
@ -241,6 +241,56 @@ class Solution:
|
|||||||
|
|
||||||
Go:
|
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
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user