Merge pull request #454 from betNevS/master

添加 0701.二叉搜索树中的插入操作 go版(迭代法)
This commit is contained in:
程序员Carl
2021-07-02 15:38:07 +08:00
committed by GitHub

View File

@ -271,6 +271,9 @@ class Solution:
Go Go
递归法
```Go ```Go
func insertIntoBST(root *TreeNode, val int) *TreeNode { func insertIntoBST(root *TreeNode, val int) *TreeNode {
if root == nil { if root == nil {
@ -285,6 +288,31 @@ func insertIntoBST(root *TreeNode, val int) *TreeNode {
return root 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版本 JavaScript版本