当前位置:网站首页>【leetcode】701. Insert operation in binary search tree

【leetcode】701. Insert operation in binary search tree

2022-06-26 15:37:00 liiiiiiiiiiiiike

For details, please refer to 701. Insert operation in binary search tree

Their thinking

  • BST characteristic , Judge root.val and val Size ,root.val < val, explain val Need to put root.right
  • conversely Put it in root.left, Judge root.right Whether there is , If there is a direct release , Otherwise, recursion insert function , Find the right place
# 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
原网站

版权声明
本文为[liiiiiiiiiiiiike]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/177/202206261521012546.html