[leetcode]701. Insert into a Binary Search Tree(Python)

[leetcode]701. Insert into a Binary Search Tree

题目描述

Category:Medium Tree

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.
在这里插入图片描述

题目理解

给定一棵二叉搜索树和一个值,返回插入该节点后的二叉搜索树的根节点。可能会有多种插入方式,返回任意一种即可。
注:该值在原二叉搜索树中不存在。

解题思路

迭代

实现思路和递归类似,若根节点为空,新建节点返回。然后用一个变量cur来遍历,若当前节点值大于插入值,判断它的左子节点是否为空,若为空,新建节点并跳出循环,否则继续遍历左子树;反之亦然。
思路借鉴:https://www.cnblogs.com/grandyang/p/9914546.html

class Solution:
	# Runtime: 136ms 85.17%  MemoryUsage: 16MB 8.00%
    def insertIntoBST1(self, root: TreeNode, val: int) -> TreeNode:
        if root is None:
            return TreeNode(val)
        cur_node = root
        while True:
            if cur_node.val > val:
                if cur_node.left is None:
                    cur_node.left = TreeNode(val)
                    break
                cur_node = cur_node.left
            else:
                if cur_node.right is None:
                    cur_node.right = TreeNode(val)
                    break
                cur_node = cur_node.right
        return root

MyMethod

递归,再加上二叉搜索树的特性:若插入值大于根节点的值,将该值插入在右子树中;若小于,则左子树。

class Solution:
    # Runtime: 144ms 36.95%  MemoryUsage: 15.1MB 100.00%
    def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
        if root is None:
            new_node = TreeNode(val)
            root = new_node
        if root.val > val:
            root.left = self.insertIntoBST(root.left, val)
        elif root.val < val:
            root.right = self.insertIntoBST(root.right, val)
        return root

Time

2020.3.28 今天要更加努力呀!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值