class TreeNode(object): #定义二叉树类
def init(self,val,left=None,right=None):
self.val = val
self.left = left
self.right = right
class BinaryTree(object):
def __init__(self,root=None):
self.root = root
def preScan(self,retList, node): #先序遍历:先跟、再左、后右
if node != None:
retList.append(node.val)
self.preScan(retList, node.left)
self.preScan(retList, node.right)
return retList
def midScan(self, retList, node): #中序遍历:先左、再跟、后右
if node != None:
self.midScan(retList, node.left)
retList.append(node.val)
self.midScan(retList, node.right)
return retList
def postScan(self, retList, node): #后序遍历:先左、再右、后跟
if node != None:
self.postScan(retList, node.left)
self.postScan(retList, node.right)
retList.append(node.val)
return retList
if __name__ == "__main__":
root = TreeNode(50)
root.left = TreeNode(20,left=TreeNode(15),right=TreeNode(30,right=TreeNode(12)))
root.right = TreeNode(60,right=TreeNode(70))
bTree = BinaryTree(root)
retList = bTree.preScan([],bTree.root)
print(retList)
retList2 = bTree.midScan([],bTree.root)
print(retList2)
retList3 = bTree.postScan([],bTree.root)
print(retList3)