二叉树的前中后遍历
class Node:
def __init__(self,data,left=None,right=None):
self.data=data
self.left=left
self.right=right
def countNode(t):
if t is None:
return 0
else:
return 1+countNode(t.left)+countNode(t.right)
def sumNode(t):
if t is None:
return 0
else:
return t.data+ sumNode(t.left) + sumNode(t.right)
def preOrder(t):
if t is None:
return
print (t.data)
preOrder(t.left)
preOrder(t.right)
def midOrder(t):
if t is None:
return
midOrder(t.left)
print(t.data)
midOrder(t.right)
def postOrder(t):
if t is None:
return
postOrder(t.left)
postOrder(t.right)
print(t.data)
def preOrderNonRec(Node):
if Node == None:
return
stack = []
while Node or stack:
while Node:
print(Node.data)
stack.append(Node)
Node = Node.left
Node = stack.pop()
Node=Node.right
def midOrderNonRec(Node):
if Node == None:
return
stack = []
while Node or stack:
while Node:
stack.append(Node)
Node = Node.left
Node = stack.pop()
print(Node.data)
Node=Node.right
def postOrderNonRec(Node):
if Node == None:
return
stack = []
while Node or stack:
while Node:
stack.append(Node)
Node = Node.left if Node.left is not None else Node.right
Node = stack.pop()
print(Node.data)
if len(stack)!=0 and stack[-1].left==Node:
Node=stack[-1].right
else:
Node=None
def BFS(Node):
if Node == None:
return
quene = []
quene.append(Node)
while quene:
Node = quene.pop(0)
print(Node.data)
if Node.left:
quene.append(Node.left)
if Node.right:
quene.append(Node.right)
if __name__ == '__main__':
t=Node(1,Node(2),Node(3))
print("前序遍历")
preOrderNonRec(t)
print("中序遍历")
midOrderNonRec(t)
print("后序遍历")
postOrderNonRec(t)
print("宽度优先遍历")
BFS(t)