mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Merge pull request #454 from betNevS/master
添加 0701.二叉搜索树中的插入操作 go版(迭代法)
This commit is contained in:
@ -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版本
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user