#二叉树前序遍历,中序遍历,后序遍历的迭代访问法
#二叉树的前序遍历迭代解法
def pre(root):
#定义一个当前节点,保存节点的栈,保存值的数组
cur,stack,res = root,[],[]
#如果是空节点就直接返回了
if not root:
return []
#如果栈中还有元素或者cur不为空
while stack or cur:
#我们就一直访问当前节点的值和他的左子节点,直到该节点为空
while cur:
res.append(cur.val)
stack.append(cur)
cur = cur.left
#我们开始往上回溯,因为当前节点的值和左子节点都被访问过了,我么直接去右子节点
cur = stack.pop()
cur = cur.right
return res
#二叉树的中序遍历迭代解法
def inorder(root):
#定义一个当前节点,保存节点的栈,保存值的数组
cur,stack,res = root,[],[]
#如果为空,就直接返回一个空列表
if not root:
return []
#如果栈中还有元素或者cur不为空
while stack or cur:
#我们保存该节点,并一直访问他的左子节点
while cur:
stack.append(cur)
cur = cur.left
#我们开始往上回溯,我们访问当前节点的值,然后去右子节点
temp = stack.pop()
res.append(temp.val)
cur = temp.right
return res
#二叉树的后序遍历迭代解法
#我们利用栈模拟后序遍历
def postOrder(root):
if not root:
return []
#只有后序遍历需要使用flag,当flag为表示我们第一次访问,flag为1我们是第二次访问,就可以访问他的值了
stack,res =[(0,root)],[]
while stack:
flag,node = stack.pop()
if not node:
continue
if flag==1:
res.append(node.val)
else:
stack.append((1,node))
stack.append((0,node.right))
stack.append((0,node.left))
return res
二叉树的前中后序遍历迭代写法
最新推荐文章于 2024-07-05 16:42:37 发布