欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python二叉树遍历的实现方法

程序员文章站 2022-09-09 08:09:39
复制代码 代码如下:#!/usr/bin/python# -*- coding: utf-8 -*- class treenode(object):  ...

复制代码 代码如下:

#!/usr/bin/python
# -*- coding: utf-8 -*-

class treenode(object):
    def __init__(self,data=0,left=0,right=0):
        self.data = data
        self.left = left
        self.right = right


class btree(object):
    def __init__(self,root=0):
        self.root = root

    def is_empty(self):
        if self.root is 0:
            return true
        else:
            return false

    def preorder(self,treenode):
        if treenode is 0:
            return
        print treenode.data
        self.preorder(treenode.left)
        self.preorder(treenode.right)

    def inorder(self,treenode):
        if treenode is 0:
            return
        self.inorder(treenode.left)
        print treenode.data
        self.inorder(treenode.right)

    def postorder(self,treenode):
        if treenode is 0:
            return
        self.postorder(treenode.left)
        self.postorder(treenode.right)
        print treenode.data


n1 = treenode(data=1)
n2 = treenode(2,n1,0)
n3 = treenode(3)
n4 = treenode(4)
n5 = treenode(5,n3,n4)
n6 = treenode(6,n2,n5)
n7 = treenode(7,n6,0)
n8 = treenode(8)
root = treenode('root',n7,n8)

bt = btree(root)
print 'preorder......'
print bt.preorder(bt.root)
print 'inorder......'
print bt.inorder(bt.root)
print 'postorder.....'
print bt.postorder(bt.root)

结果:

preorder......
root
7
6
2
1
5
3
4
8

inorder......
1
2
6
3
5
4
7
root
8

postorder.....
1
2
3
4
5
6
7
8
root