【leetcode】701. Insertion operation in binary search tree

For details, see 701. Insertion operations in binary search trees

problem solving ideas

  • BST feature, judge the size of root.val and val, root.val < val, indicating that val needs to be placed in root.right
  • On the contrary, put it in root.left, judge whether root.right exists, if it exists, put it directly, otherwise recursively insert function, find a suitable position
# 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: TreeNode, val: int) -> TreeNode:
        if not root:
            return TreeNode(val)
        def insert(root):
            if root.val < val:
                if root.right:
                    insert(root.right)
                else:
                    root.right = TreeNode(val)
            else:
                if root.left:
                    insert(root.left)
                else:
                    root.left = TreeNode(val)
        insert(root)
        return root

Guess you like

Origin blog.csdn.net/weixin_45074568/article/details/125468096