1.测试用例:
先序遍历:DBACEGF
中序遍历:ABCDEFG
后序遍历:ACBFGED
2.编写python代码:
class Node:
def __init__(self,value=None,left=None,right=None):
self.value=value
self.left=left
self.right=right
def preTraverse(root):
if root==None:
return
print(root.value)
preTraverse(root.left)
preTraverse(root.right)
def midTraverse(root):
if root==None:
return
midTraverse(root.left)
print(root.value)
midTraverse(root.right)
def afterTraverse(root):
if root==None:
return
afterTraverse(root.left)
afterTraverse(root.right)
print(root.value)
if __name__=='__main__':
root=Node('D',Node('B',Node('A'),Node('C')),Node('E',right=Node('G',Node('F'))))
print('NLR:')
preTraverse(root)
print('LNR:')
midTraverse(root)
print('LRN:')
afterTraverse(root)
3.运行结果:
|