Python實現簡單二叉樹

class BinaryTree:
    def __init__(self,rootObj):
        self.root = rootObj
        self.leftChild = None
        self.rightChild = None

    def insertLeft(self,newNode):
        if self.leftChild == None:
            self.leftChild = BinaryTree(newNode)
        else:
            print('The leftChild is not None.You can not insert')
    def insertRight(self,newNode):
        if self.rightChild == None:
            self.rightChild = BinaryTree(newNode)
        else:
            print('The rightChild is not None.You can not insert')
  • 構建了一個簡單的二叉樹類,它的初始化函數,將傳入的rootObj賦值給self.root,作爲根節點,leftChild和rightChild都默認爲None。

  • 函數insertLeft爲向二叉樹的左子樹賦值,若leftChild爲空,則先構造一個BinaryTree(newNode),即實例化一個新的二叉樹,然後將這棵二叉樹賦值給原來的二叉樹的leftChild。此處遞歸調用了BinaryTree這個類。

  • 若不爲空 則輸出:The rightChild is not None.You can not insert

執行下述語句

r = BinaryTree('a')
print('root:',r.root,';','leftChild:',r.leftChild,';','rightChild:',r.rightChild)

輸出

root: a ; leftChild: None ; rightChild: None
  • 即我們構造了一顆二叉樹,根節點爲a,左右子樹均爲None

然後執行下述語句

r.insertLeft('b')
print('root:',r.root,';','leftChild:',r.leftChild,';','rightChild:',r.rightChild)
print('root:',r.root,';','leftChild.root:',r.leftChild.root,';','rightChild:',r.rightChild)

輸出

root: a ; leftChild: <__main__.BinaryTree object at 0x000002431E4A0DA0> ; rightChild: None
root: a ; leftChild.root: b ; rightChild: None
  • 我們向r插入了一個左節點,查看輸出的第一句話,可以看到左節點其實也是一個BinaryTree,這是因爲插入時,遞歸生成的。

  • 第二句輸出,可以查看左節點的值

最後執行

r.insertLeft('c')
The leftChild is not None.You can not insert
  • 可以看到,我們無法再向左節點插入了,因爲該節點已經有值了
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章