mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 15:45:40 +08:00
添加 0701.二叉搜索树中的插入操作 go版(迭代法)
This commit is contained in:
@ -271,6 +271,9 @@ class Solution:
|
||||
|
||||
|
||||
Go:
|
||||
|
||||
递归法
|
||||
|
||||
```Go
|
||||
func insertIntoBST(root *TreeNode, val int) *TreeNode {
|
||||
if root == nil {
|
||||
@ -285,6 +288,31 @@ func insertIntoBST(root *TreeNode, val int) *TreeNode {
|
||||
return root
|
||||
}
|
||||
```
|
||||
迭代法
|
||||
```go
|
||||
func insertIntoBST(root *TreeNode, val int) *TreeNode {
|
||||
if root == nil {
|
||||
return &TreeNode{Val:val}
|
||||
}
|
||||
node := root
|
||||
var pnode *TreeNode
|
||||
for node != nil {
|
||||
if val > node.Val {
|
||||
pnode = node
|
||||
node = node.Right
|
||||
} else {
|
||||
pnode = node
|
||||
node = node.Left
|
||||
}
|
||||
}
|
||||
if val > pnode.Val {
|
||||
pnode.Right = &TreeNode{Val: val}
|
||||
} else {
|
||||
pnode.Left = &TreeNode{Val: val}
|
||||
}
|
||||
return root
|
||||
}
|
||||
```
|
||||
|
||||
JavaScript版本
|
||||
|
||||
|
Reference in New Issue
Block a user