【数据结构】二叉树的深度优先遍历DFS
深度优先是用栈,先进后出;(二叉树的深度优先遍历就是先序遍历)
广度优先是用堆,先进先出。
深度优先搜索二叉树是先访问根结点,然后遍历左子树接着是遍历右子树,因此我们可以利用栈的先进后出的特点,
先将右子树压栈,再将左子树压栈,这样左子树就位于栈顶,可以保证结点的左子树先与右子树被遍历。
代码:
# 深度优先遍历
def dfs(self,root):
stack = []
rs = []
if root:
stack.append(root)
while stack:
cur = stack.pop()
# print(cur.val)
rs.append(cur.val)
if cur.right:
stack.append(cur.right)
if cur.left:
stack.append(cur.left)
print(rs)
顺便复习一下广度优先遍历——层次遍历:
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
queue = []
rs = []
if root:
queue.append(root)
while queue:
cur_level,size = [],len(queue)
for _ in range(size):
tmp = queue.pop(0)
cur_level.append(tmp.val)
if tmp.left:
queue.append(tmp.left)
if tmp.right:
queue.append(tmp.right)
rs.append(cur_level[:])
return rs