class NodeClass:
def __init__(self, element):
self.element = element
self.left = None
self.right = None
returnPreList = []
def pre_digui(root): # 前序遍历 递归
if root:
returnPreList.append(root.element)
pre_digui(root.left)
pre_digui(root.right)
def pre_duizhan(root): # 前序 堆栈
returnList = []
nodeList = []
node = root
while nodeList or node:
while node:
nodeList.append(node)
returnList.append(node.element)
node = node.left
node = nodeList.pop()
node = node.right
print(returnList)
returnMidList = []
def mid_digui(root): # 中序递归
if root:
mid_digui(root.left)
returnMidList.append(root.element)
mid_digui(root.right)
def mid_duizhan(root): # 中序堆栈
returnList = []
nodeList = []
node = root
while nodeList or node:
while node:
nodeList.append(node)
node = node.left
node = nodeList.pop()
returnList.append(node.element)
node = node.right
print(returnList)
returnPostList = []
def post_digui(root): # 后序递归
if root:
post_digui(root.left)
post_digui(root.right)
returnPostList.append(root.element)
def post_duizhan(root): # 后序堆栈
returnList = []
tempList = [root]
while tempList:
temp = tempList.pop()
if type(temp) is NodeClass:
tempList.append(temp.element)
if temp.right:
tempList.append(temp.right)
if temp.left:
tempList.append(temp.left)
else:
returnList.append(temp)
print(returnList)
def post_duizhan2(root): # 后序堆栈方法2
returnList = []
nodeList1 = [root]
nodeList2 = []
while nodeList1:
node = nodeList1.pop()
nodeList2.append(node)
if node.left:
nodeList1.append(node.left)
if node.right:
nodeList1.append(node.right)
while nodeList2:
returnList.append(nodeList2.pop().element)
print(returnList)
root = NodeClass(0)
root.left = NodeClass(1)
root.right = NodeClass(2)
root.left.left = NodeClass(3)
root.left.right = NodeClass(4)
root.right.left = NodeClass(5)
root.right.right = NodeClass(6)
# pre_digui(root)
# print(returnPreList)
# pre_duizhan(root)
# mid_digui(root)
# print(returnMidList)
# mid_duizhan(root)
post_digui(root)
print(returnPostList)
post_duizhan(root)
post_duizhan2(root)
二叉树前序、中序、后序遍历递归、非递归
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 最近又有面试,懒得复习代码了,干脆把代码翻到简书上,偶尔看看 问题: 1、给二叉树中序和前序,指针建树 2、给后序...
- 如下图,对图中二叉树遍历: 先序为:ABDNCEFGHIJKLMOQP中序为:DNBCGFEAHJKILOQMP后...