@@ -283,32 +283,10 @@ class Solution:
283283 return TreeNode(val)
284284 self .traversal(root, val)
285285 return root
286-
287286```
288287
289288递归法(版本二)
290289``` python
291- class Solution :
292- def insertIntoBST (self , root , val ):
293- if root is None :
294- return TreeNode(val)
295- parent = None
296- cur = root
297- while cur:
298- parent = cur
299- if val < cur.val:
300- cur = cur.left
301- else :
302- cur = cur.right
303- if val < parent.val:
304- parent.left = TreeNode(val)
305- else :
306- parent.right = TreeNode(val)
307- return root
308- ```
309-
310- 递归法(版本三)
311- ``` python
312290class Solution :
313291 def insertIntoBST (self , root : Optional[TreeNode], val : int ) -> Optional[TreeNode]:
314292 if root is None or root.val == val:
@@ -326,7 +304,7 @@ class Solution:
326304 return root
327305```
328306
329- 递归法(版本四 )
307+ 递归法(版本三 )
330308``` python
331309class Solution :
332310 def insertIntoBST (self , root , val ):
@@ -340,10 +318,9 @@ class Solution:
340318 root.right = self .insertIntoBST(root.right, val)
341319
342320 return root
343-
344321```
345322
346- 迭代法
323+ 迭代法(版本一)
347324``` python
348325class Solution :
349326 def insertIntoBST (self , root , val ):
@@ -366,10 +343,53 @@ class Solution:
366343 else :
367344 parent.right = node # 将新节点连接到父节点的右子树
368345
346+ return root
347+ ```
348+
349+ 迭代法(版本二)
350+ ``` python
351+ class Solution :
352+ def insertIntoBST (self , root , val ):
353+ if root is None :
354+ return TreeNode(val)
355+ parent = None
356+ cur = root
357+ while cur:
358+ parent = cur
359+ if val < cur.val:
360+ cur = cur.left
361+ else :
362+ cur = cur.right
363+ if val < parent.val:
364+ parent.left = TreeNode(val)
365+ else :
366+ parent.right = TreeNode(val)
369367 return root
368+ ```
369+
370+ 迭代法(精简)
371+ ``` python
372+ class Solution :
373+ def insertIntoBST (self , root : Optional[TreeNode], val : int ) -> Optional[TreeNode]:
374+ if not root: # 如果根节点为空,创建新节点作为根节点并返回
375+ return TreeNode(val)
376+ cur = root
377+ while cur:
378+ if val < cur.val:
379+ if not cur.left: # 如果此时父节点的左子树为空
380+ cur.left = TreeNode(val) # 将新节点连接到父节点的左子树
381+ return root
382+ else :
383+ cur = cur.left
384+ elif val > cur.val:
385+ if not cur.right: # 如果此时父节点的左子树为空
386+ cur.right = TreeNode(val) # 将新节点连接到父节点的右子树
387+ return root
388+ else :
389+ cur = cur.right
370390
371-
372391```
392+
373393-----
374394### Go
375395
0 commit comments