python二叉树

本文阅读 1 分钟
首页 › Python笔记 › 正文
class BinaryTree:
    def __init__(self, rootObj):
        self.key = rootObj
        self.leftChild = None
        self.rightChild = None

    def insertLeft(self, newNode):
        if self.leftChild == None:
            self.leftChild = BinaryTree(newNode)
        else:
            t = BinaryTree(newNode)
            t.leftChild = self.leftChild
            self.leftChild = t

    def insertRight(self, newNode):
        if self.rightChild == None:
            self.rightChild = BinaryTree(newNode)
        else:
            t = BinaryTree(newNode)
            t.rightChild = self.rightChild
            self.rightChild = t

    def getRightChild(self):
        return self.rightChild

    def getLeftChild(self):
        return self.leftChild

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

    def getRootVal(self):
        return self.key

    # 树的前序遍历
    # 树的后序遍历以及中序遍历见ParseTree.py
    def preorder(self):
        print(self.key)
        if self.leftChild:
            self.leftChild.preorder()
        if self.rightChild:
            self.rightChild.preorder()

'''
以下为测试数据, 去掉 # 即可
'''
# r = BinaryTree('a')
# print(r.getRootVal())
# print(r.getLeftChild())
# r.insertLeft('b')
# print(r.getLeftChild())
# print(r.getLeftChild().getRootVal())
# r.insertRight('c')
# print(r.getRightChild())
# print(r.getRightChild().getRootVal())
# r.getRightChild().setRootVal('hello')
# print(r.getRightChild().getRootVal())
python二分查找
« 上一篇 01-21
Python 实现冒泡排序
下一篇 » 01-21

发表评论

惪特博客
  • 文章总数:
    5298 篇
  • 评论总数:
    53894 条
  • 标签总数:
    6607 个
  • 总浏览量:
    37577663 次
  • 最后更新:
    昨天 09:44

最多点赞

随便看看

标签TAG