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

题目详见 701. 二叉搜索树中的插入操作

解题思路

  • BST特性,判断root.val和val的大小,root.val < val, 说明val需要放到 root.right
  • 反之 放到root.left,判断root.right是否存在,如果存在直接放,否则就递归insert函数,找到合适位置
# 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

猜你喜欢

转载自blog.csdn.net/weixin_45074568/article/details/125468096
今日推荐