第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定

[碩.Love Python] BinarySearchTree(二叉搜索樹)

class Node(object):
    __slots__ = ['left', 'right', 'data']

    def __init__(self, data, left=None, right=None):
        self.data = data
        self.left = left
        self.right = right

    def __str__(self):
        sl = '%s <-' % self.left if self.left else ''
        sr = '-> %s' % self.right if self.right else ''
        return '[%s Node(%s) %s]' % (sl, self.data, sr)

class BinarySearchTree(object):
    def __init__(self):
        self.root = None

    def insert(self, data):
        node, parent = self.search(data, True)
        if node:
            raise ValueError('"%s" has been in tree.' % data)

        node = Node(data)
        if parent is None:
            self.root = node
        elif data < parent.data:
            parent.left = node
        else:
            parent.right = node 

    def search(self, data, retParent=False):
        parent = None
        node = self.root

        while node and node.data != data:
            parent = node
            if data < node.data:
                node = node.left
            else:
                node = node.right

        return (node, parent) if retParent else node

    def delete(self, data):
        self._deleteNode(*self.search(data, True))

    def _findBiggest(self, node):
        parent = None
        while node.right:
            parent = node
            node = node.right
        return node, parent

    def _deleteNode(self, node, parent):
        if node is None:
            return 

        if node.left and node.right:
            tmp, tmpParent = self._findBiggest(node.left)
            if tmpParent is not None:
                tmpParent.right = tmp.left
                tmp.left = node.left 
            tmp.right = node.right
        else:
            tmp = node.left or node.right

        if parent is None:
            self.root = tmp
        elif parent.left is node:
            parent.left = tmp
        else:
            parent.right = tmp

if __name__ == '__main__':
    bst = BinarySearchTree()
    while True:
        cmd = (raw_input('$ ')).strip().split()
        if cmd[0] == 'i':
            bst.insert(int(cmd[1]))
            print bst.root
        elif cmd[0] == 'd':
            bst.delete(int(cmd[1]))
            print bst.root
點(diǎn)擊查看更多內(nèi)容
2人點(diǎn)贊

若覺得本文不錯(cuò),就分享一下吧!

評(píng)論

作者其他優(yōu)質(zhì)文章

正在加載中
感謝您的支持,我會(huì)繼續(xù)努力的~
掃碼打賞,你說多少就多少
贊賞金額會(huì)直接到老師賬戶
支付方式
打開微信掃一掃,即可進(jìn)行掃碼打賞哦
今天注冊(cè)有機(jī)會(huì)得

100積分直接送

付費(fèi)專欄免費(fèi)學(xué)

大額優(yōu)惠券免費(fèi)領(lǐng)

立即參與 放棄機(jī)會(huì)
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)

舉報(bào)

0/150
提交
取消