701. 二叉搜索树中的插入操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
# 最简单的方法,当然是直接加到 bst的 叶子结点上。
if root==None:
return TreeNode(val=val)
if root.val > val:
root.left = self.insertIntoBST(root.left,val)
elif root.val < val:
root.right = self.insertIntoBST(root.right,val)
return root