class TreeNode:
def __init__(self,val):
super(TreeNode).__init__()
self.val = val
self.left = None
self.right = None
self.isPop = False
def createTree(valList):
if not valList:
raise ValueError("input value list is None!")
root = TreeNode(valList[0])
valList.pop(0)
layerOne = [root]
layerTwo = []
i = 0
while i<len(valList):
n = layerOne.pop(0)
if valList[i] is not None:
n.left = TreeNode(valList[i])
layerOne.append(n.left)
i = i+1
if i<len(valList) and valList[i] is not None:
n.right = TreeNode(valList[i])
layerOne.append(n.right)
i = i+1
return root
valList = [1,2,3,4,None,6,7,8,9,None,11,12,13]
root = createTree(valList)
def inOrder(root):
stack = []
p = root
while stack or p:
if p:
stack.append(p)
p = p.left
else:
p = stack.pop()
print(p.val,end = " ")
p = p.right
print()
def preOrder(root):
if not root:
return
stack = [root]
while stack:
p = stack.pop()
print(p.val,end=" ")
if p.right:
stack.append(p.right)
if p.left:
stack.append(p.left)
print()
def postOrder(root):
def operate(node,stack):
if node.left is None and node.right is None or node.isPop:
print(node.val,end=" ")
else:
stack.append(node)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return stack
if not root:
return
stack = [root]
while stack:
p = stack.pop()
stack=operate(p,stack)
p.isPop = True
preOrder(root) #1 2 4 8 9 3 6 11 7 12 13
inOrder(root) #8 4 9 2 1 6 11 3 12 7 13
postOrder(root) #8 9 4 2 11 6 12 13 7 3 1
后序遍历的实现方法中,改变节点的入栈顺序也可以用来实现另外两种遍历