LeetCode | 0701. Insert into a Binary Search Tree 二叉搜索樹中的插入操作【Python】

LeetCode 0701. Insert into a Binary Search Tree 二叉搜索樹中的插入操作【Medium】【Python】【二叉樹】

Problem

LeetCode

Given the root node of a binary search tree (BST) and a value to be inserted into the tree, insert the value into the BST. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.

Note that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.

For example,

Given the tree:
        4
       / \
      2   7
     / \
    1   3
And the value to insert: 5

You can return this binary search tree:

         4
       /   \
      2     7
     / \   /
    1   3 5

This tree is also valid:

         5
       /   \
      2     7
     / \   
    1   3
         \
          4

Constraints:

  • The number of nodes in the given tree will be between 0 and 10^4.
  • Each node will have a unique integer value from 0 to -10^8, inclusive.
  • -10^8 <= val <= 10^8
  • It’s guaranteed that val does not exist in the original BST.

問題

力扣

給定二叉搜索樹(BST)的根節點和要插入樹中的值,將值插入二叉搜索樹。 返回插入後二叉搜索樹的根節點。 保證原始二叉搜索樹中不存在新值。

注意,可能存在多種有效的插入方式,只要樹在插入後仍保持爲二叉搜索樹即可。 你可以返回任意有效的結果。

例如,

給定二叉搜索樹:

    4
   / \
  2   7
 / \
1   3

和 插入的值: 5
你可以返回這個二叉搜索樹:

     4
   /   \
  2     7
 / \   /
1   3 5

或者這個樹也是有效的:

     5
   /   \
  2     7
 / \   
1   3
     \
      4

思路

二叉樹

Python3代碼
# 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)
        if root.val < val:
            root.right = self.insertIntoBST(root.right, val)
        if root.val > val:
            root.left = self.insertIntoBST(root.left, val)
        return root

GitHub鏈接

Python

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章