LC701. 二叉搜索树中的插入操作

先找到插入位置,之后需要连接到树上

def insertIntoBST(self, root, val):
        """
        :type root: TreeNode
        :type val: int
        :rtype: TreeNode
        """
        if not root:
            return TreeNode(val)
        if root.val > val:
            root.left = self.insertIntoBST(root.left,val)
        if root.val < val:
            root.right = self.insertIntoBST(root.right,val)
        return root

不直接返回值

def insertIntoBST(self, root, val):
        parent = None
        if not root: 
            return TreeNode(val)
        def traverse(cur, val): 
            global parent # 在函数运行的同时把新节点插入到该被插入的地方. 
            if not cur:   #这里说明找到了插入的位置,然后判断一下是放在左边还是右边
                new_node = TreeNode(val)
                if parent.val < val: 
                    parent.right = new_node
                else: 
                    parent.left = new_node
                return 
            parent = cur    # 这里的parent记录要插入的位置,是cur的父节点.
            if cur.val < val: 
                traverse(cur.right, val)
            else: 
                traverse(cur.left, val)
        traverse(root, val)
        return root

迭代

def insertIntoBST(self, root, val):
        """
        :type root: TreeNode
        :type val: int
        :rtype: TreeNode
        """
        if not root:
            return TreeNode(val)
        parent = None
        roott = root
        while root:
            if root.val > val:
                parent = root
                root = root.left
            else:
                parent = root
                root = root.right
        if parent.val > val:
            parent.left = TreeNode(val)
        else:
            parent.right = TreeNode(val)
        return roott
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值