图的遍历

实现下图图的遍历关于深度广度优先遍历,先访问左边节点

深度优先遍历:

function depthFirstTraversal(node):
if node is null:
return
visit(node)
depthFirstTraversal(node.left)
depthFirstTraversal(node.right)

广度优先遍历:

function breadthFirstTraversal(root):
if root is null:
return
queue = new Queue()
queue.enqueue(root)
while queue is not empty:
node = queue.dequeue()
visit(node)
if node.left is not null:
queue.enqueue(node.left)
if node.right is not null:
queue.enqueue(node.right)

posted @ 2023-11-11 11:18  20231317莫善燎  阅读(5)  评论(0编辑  收藏  举报