【python中二叉树的实现】python中二叉树的创建、三种方式递归遍历和非递归遍历

时间:2022-06-25 14:34:54

代码如下:

# coding=utf-8

class myNode(object):
def __init__(self, data=-1, lchild=None, rchild=None):
self.data = data
self.lchild = lchild
self.rchild = rchild class BTTree(object):
def __init__(self):
self.root = None # 建立二叉树是以层序遍历方式输入,节点不存在时以 'None' 表示
def creatTree(self, nodeList):
if nodeList[0] == None:
return None
head = myNode(nodeList[0])
Nodes = [head]
j = 1
for node in Nodes:
if node != None:
node.lchild = (myNode(nodeList[j]) if nodeList[j] != None else None)
Nodes.append(node.lchild)
j += 1
if j == len(nodeList):
return head
node.rchild = (myNode(nodeList[j])if nodeList[j] != None else None)
j += 1
Nodes.append(node.rchild)
if j == len(nodeList):
return head def digui_qianxu(self, root):
if root is None:
return
print root.data
self.digui_qianxu(root.lchild)
self.digui_qianxu(root.rchild) def digui_zhongxu(self, root):
if root is None:
return
self.digui_zhongxu(root.lchild)
print root.data
self.digui_zhongxu(root.rchild) def digui_houxu(self, root):
if root is None:
return
self.digui_houxu(root.lchild)
self.digui_houxu(root.rchild)
print root.data def feidigui_qianxu(self, root):
#通过堆栈来存储根节点,遍历根节点从root开始一直往下走到最左边的根节点将之加入到栈中,在加入栈中之前就进行访问
#将栈中的内容不断从最后弹出,然后查找其是否有右孩子,没有则继续弹出栈中的元素,有的话则访问
myStack = []
node = root
while node or myStack:
while node!= None:
print node.data
myStack.append(node)
node = node.lchild
elem = myStack.pop()
if elem.rchild != None:
node = elem.rchild def feidigui_zhongxu(self, root):
myStack = []
node = root
while node or myStack:
while node != None:
myStack.append(node)
node = node.lchild
elem = myStack.pop()
print elem.data
if elem.rchild != None:
node = elem.rchild def feidigui_houxu(self, root):
#因为是左右然后根,需要保留根才能得到左和右,首先从根pop之后找到左加入到栈,找到右加入到栈
#之后将根加入到另一个栈中,这样另一个栈中得到的就是:根右左的顺序
#等将另一个栈进行持续pop,得到的就是:左右根这样的顺序
myStack1 = []
myStack2 = []
myStack1.append(root)
while myStack1:
node = myStack1.pop()
if node.lchild != None:
myStack1.append(node.lchild)
if node.rchild != None:
myStack1.append(node.rchild)
myStack2.append(node)
while myStack2:
print myStack2.pop().data if __name__ == "__main__":
test1 = BTTree()
nodeList = [1,2,3,4,5,6]
print '建树:'
test1.root = test1.creatTree(nodeList)
print '递归前序:'
test1.digui_qianxu(test1.root)
print '----------------------'
print '递归中序:'
test1.digui_zhongxu(test1.root)
print '----------------------'
print '递归后序:'
test1.digui_houxu(test1.root)
print '----------------------'
print '非递归前序:'
test1.feidigui_qianxu(test1.root)
print '----------------------'
print '非递归中序:'
test1.feidigui_zhongxu(test1.root)
print '----------------------'
print '非递归后序:'
test1.feidigui_houxu(test1.root)
print '----------------------'

结果如下:

建树:
递归前序:
1
2
4
5
3
6
----------------------
递归中序:
4
2
5
1
6
3
----------------------
递归后序:
4
5
2
6
3
1
----------------------
非递归前序:
1
2
4
5
3
6
----------------------
非递归中序:
4
2
5
1
6
3
----------------------
非递归后序:
4
5
2
6
3
1
----------------------