zoukankan      html  css  js  c++  java
  • 树进行广度优先遍历(BFS),深度优先遍历(DFS),Python迭代法实现

    广度优先遍历

    广度遍历又叫层次遍历。用队列实现,依次将根,左子树,右子树存入队列,按照队列的先进先出规则来实现层次遍历。

    # 层次遍历(广度优先)
    def BFS(root):
        if root:
            res = []
            queue = [root]
            while queue:
                currentNode = queue.pop(0)
                res.append(currentNode.val)
                if currentNode.left:
                    queue.append(currentNode.left)
                if currentNode.right:
                    queue.append(currentNode.right)
        return res

    深度优先遍历

    用栈实现,先将根入栈,再将根出栈,并将根的右子树,左子树存入栈,按照栈的先进后出规则来实现深度优先遍历。

    # 深度优先
    def DFS(root):
        if root:
            res = []
            stack = [root]
            while stack:
                currentNode = stack.pop()
                res.append(currentNode.val)
                if currentNode.right:
                    stack.append(currentNode.right)
                if currentNode.left:
                    stack.append(currentNode.left)
        return res
  • 相关阅读:
    前端开发—HTML
    初识 Django
    前端开发—BOM对象DOM文档对象操作
    前端开发—jQuery
    前端开发—Javascript
    前端开发—CSS 盒子、浮动、定位
    前端开发—CSS
    html模拟手机页面
    人类简史读书笔记
    正则表达式
  • 原文地址:https://www.cnblogs.com/geeksongs/p/15389799.html
Copyright © 2011-2022 走看看