class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def preOrder(root):
if not root:
return
print(root.val, end=" ")
preOrder(root.left)
preOrder(root.right)
def preOrderIterV1(root):
if not root:
return
stack = [root]
while stack:
now = stack.pop()
print(now.val, end=" ")
if now.right:
stack.append(now.right)
if now.left:
stack.append(now.left)
def preOrderIterV2(root):
if not root:
return
stack = []
cur = root
while cur or stack:
while cur:
print(cur.val, end=" ")
stack.append(cur)
cur = cur.left
cur = stack.pop()
cur = cur.right
def inOrder(root):
if not root:
return
inOrder(root.left)
print(root.val, end=" ")
inOrder(root.right)
def inOrderIter(root):
if not root:
return
stack = []
node = root
while node or stack:
while node:
stack.append(node)
node = node.left
node = stack.pop()
print(node.val, end=" ")
node = node.right
def postOrder(root):
if not root:
return
postOrder(root.left)
postOrder(root.right)
print(root.val, end=" ")
def postOrderIterV1(root):
"""根、右、左的顺序先序遍历,然后逆序输出"""
if not root:
return
result = []
stack = []
cur = root
while cur or stack:
while cur:
result.append(cur.val)
stack.append(cur)
cur = cur.right
cur = stack.pop()
cur = cur.left
for i in range(len(result)-1, -1, -1):
print(result[i], end=" ")
def postOrderIterV2(root):
if not root:
return
result = []
stack = [root]
while stack:
now = stack.pop()
result.append(now.val)
if now.left:
stack.append(now.left)
if now.right:
stack.append(now.right)
for i in range(len(result)-1, -1, -1):
print(result[i], end=" ")
demo = TreeNode(0)
demo.left = TreeNode(1)
demo.right = TreeNode(2)
demo.left.left = TreeNode(3)
demo.left.right = TreeNode(4)
demo.right.right = TreeNode(5)
# 先序遍历
print("递归/迭代先序遍历:")
preOrder(demo)
print()
preOrderIterV1(demo)
print()
preOrderIterV2(demo)
print()
# 中序遍历
print("递归/迭代中序遍历:")
inOrder(demo)
print()
inOrderIter(demo)
print()
# 后序遍历
print("递归/迭代后序遍历:")
postOrder(demo)
print()
postOrderIterV1(demo)
print()
postOrderIterV2(demo)
print()
"""
二叉树为:
0
/ \
1 2
/ \ \
3 4 5
递归/迭代先序遍历:
0 1 3 4 2 5
0 1 3 4 2 5
0 1 3 4 2 5
递归/迭代中序遍历:
3 1 4 0 2 5
3 1 4 0 2 5
递归/迭代后序遍历:
3 4 1 5 2 0
3 4 1 5 2 0
3 4 1 5 2 0
"""