Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitf04f4e7

Browse files
Merge pull requestyoungyangyang04#454 from betNevS/master
添加 0701.二叉搜索树中的插入操作 go版(迭代法)
2 parents15582ef +d5e128e commitf04f4e7

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

‎problems/0701.二叉搜索树中的插入操作.md

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -271,6 +271,9 @@ class Solution:
271271

272272

273273
Go:
274+
275+
递归法
276+
274277
```Go
275278
funcinsertIntoBST(root *TreeNode,valint) *TreeNode {
276279
if root ==nil {
@@ -285,6 +288,31 @@ func insertIntoBST(root *TreeNode, val int) *TreeNode {
285288
return root
286289
}
287290
```
291+
迭代法
292+
```go
293+
funcinsertIntoBST(root *TreeNode,valint) *TreeNode {
294+
if root ==nil {
295+
return &TreeNode{Val:val}
296+
}
297+
node:= root
298+
varpnode *TreeNode
299+
for node !=nil {
300+
if val > node.Val {
301+
pnode = node
302+
node = node.Right
303+
}else {
304+
pnode = node
305+
node = node.Left
306+
}
307+
}
308+
if val > pnode.Val {
309+
pnode.Right = &TreeNode{Val: val}
310+
}else {
311+
pnode.Left = &TreeNode{Val: val}
312+
}
313+
return root
314+
}
315+
```
288316

289317
JavaScript版本
290318

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp