1. 程式人生 > >14_資料結構與演算法_二叉樹_Python實現

14_資料結構與演算法_二叉樹_Python實現

#Created By: Chen Da


class BinaryTree(object):
    def __init__(self,rootObj):
        self.key = rootObj
        self.left_child = None
        self.right_child = None

    def insert_left(self,new_node):
        if self.left_child == None:
            self.left_child = BinaryTree(new_node)
        else:
            tree_ = BinaryTree(new_node)
            tree_.left_child = self.left_child      #插入一個節點
            self.left_child = tree_                 #將原有的子節點放在樹的下一層

    def insert_right(self,new_node):
        if self.right_child == None:
            self.right_child = BinaryTree(new_node)
        else:
            tree_ = BinaryTree(new_node)
            tree_.left_child = self.left_child
            self.left_child = tree_

    def get_right_child(self):
        return self.right_child

    def get_left_child(self):
        return self.left_child

    def set_root_val(self,obj):
        self.key = obj

    def get_root_val(self):
        return self.key

def test_BinaryTree():
    tree1 = BinaryTree('a')
    assert tree1.get_root_val() == 'a'
    tree1.insert_left('b')
    tree1.insert_right('c')
    tree1.set_root_val('d')
    assert tree1.get_root_val() == 'd'
    print(tree1.left_child)
    print(tree1.right_child)

if __name__ == "__main__":
    test_BinaryTree()