From d5e128e20921517085aa199e3a0667e8c2c252de Mon Sep 17 00:00:00 2001 From: NevS <1173325467@qq.com> Date: Thu, 1 Jul 2021 23:13:32 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200701.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=90=9C=E7=B4=A2=E6=A0=91=E4=B8=AD=E7=9A=84=E6=8F=92=E5=85=A5?= =?UTF-8?q?=E6=93=8D=E4=BD=9C=20go=E7=89=88=EF=BC=88=E8=BF=AD=E4=BB=A3?= =?UTF-8?q?=E6=B3=95=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0701.二叉搜索树中的插入操作.md | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/problems/0701.二叉搜索树中的插入操作.md b/problems/0701.二叉搜索树中的插入操作.md index 794e0ae2..61027453 100644 --- a/problems/0701.二叉搜索树中的插入操作.md +++ b/problems/0701.二叉搜索树中的插入操作.md @@ -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版本