python 实现 二叉树的三种遍历方式

  • Post author:
  • Post category:python

前序遍历:根左右
中序遍历:左根右
后续遍历:左右根

class Binarytree(object):
    result = []

    # 构造
    def __init__(self, value=None, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right

    def min_tra(self, root):#中序遍历
        if root is not None:
            self.min_tra(root.left)
            Binarytree.result.append(root.value)
            self.min_tra(root.right)
        else:
            return

    def front_tra(self,root):#前序遍历
        if root is None:
            return
        self.result.append(root.value)
        self.front_tra(root.left)
        self.front_tra(root.right)

    def behind_tra(self, root):#后序遍历
        if root is None:
            return
        self.behind_tra(root.left)
        self.behind_tra(root.right)
        self.result.append(root.value)



if __name__ == '__main__':
    a = Binarytree()
    b = Binarytree()
    c = Binarytree()
    a.value = 9
    b.value = 10
    c.value = 15
    a.left = b
    a.right = c
    a.behind_tra(a)
    print(Binarytree.result)


版权声明:本文为weixin_43092885原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。