前中后序遍历(非递归) python

树通常都要用stack辅助栈。
思路:左边的树节点先进栈,每次输出最后一个节点,在寻找右边的节点(中间的节点就是上一层的左节点)。

中序遍历:左中右

res=[]
tmp=[]
cur=root
while cur or tmp:
	if cur:
		tmp.append(cur)
		cur=cur.left
	else:
		cur=tmp.pop()
		res.append(cur.val)
		cur=cur.right
return res

———————————————————————————————————————————————
前序遍历:中左右

res=[]
tmp=[]
cur=root
while cur or tmp:
	if cur:
		res.append(cur.val)
		tmp.append(cur.right)
		cur=cur.left
	else:
		cur=tmp.pop()
return res

———————————————————————————————————————————————
后序遍历:左右中(就是中右左的逆序,但是中左右已经有了,所以只要先序修改左右位置了。)

res=[]
tmp=[]
cur=root
while cur or tmp:
	if cur:
		res.append(cur.val)
		tmp.append(cur.left)
		cur=cur.right
	else:
		cur=tmp.pop()
return res[::-1]
发布了69 篇原创文章 · 获赞 46 · 访问量 5249

猜你喜欢

转载自blog.csdn.net/qq_42738654/article/details/104300604