class ListNode(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
# 递归实现先序遍历
def pre_order(root):
if root is None:
return
# 先打印节点值
print(root.data)
pre_order(root.left)
pre_order(root.right)
# 非递归实现前序遍历
def pre_order_not_rec(root):
stack = []
while root or stack:
while root:
print(root.val)
stack.append(root) # 将该节点压入栈,因为右孩子没有被访问
root = root.left # 访问左孩子左孩子
root = stack.pop()
root = root.right
二叉树的先序遍历
最新推荐文章于 2022-07-20 10:11:27 发布