mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-06 23:28:29 +08:00
修改0701.二叉搜索树中的插入操作,增加python版本的迭代法(精简)
This commit is contained in:
@ -370,6 +370,30 @@ class Solution:
|
||||
|
||||
|
||||
```
|
||||
|
||||
迭代法(精简)
|
||||
```python
|
||||
class Solution:
|
||||
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
|
||||
if not root: # 如果根节点为空,创建新节点作为根节点并返回
|
||||
return TreeNode(val)
|
||||
cur = root
|
||||
while cur:
|
||||
if val < cur.val:
|
||||
if not cur.left: # 如果此时父节点的左子树为空
|
||||
cur.left = TreeNode(val) # 将新节点连接到父节点的左子树
|
||||
return root
|
||||
else:
|
||||
cur = cur.left
|
||||
elif val > cur.val:
|
||||
if not cur.right: # 如果此时父节点的左子树为空
|
||||
cur.right = TreeNode(val) # 将新节点连接到父节点的右子树
|
||||
return root
|
||||
else:
|
||||
cur = cur.right
|
||||
|
||||
```
|
||||
|
||||
-----
|
||||
### Go
|
||||
|
||||
|
Reference in New Issue
Block a user