栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python树的深度优先遍历广度优先遍历

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python树的深度优先遍历广度优先遍历

广度优先(层次遍历)

从树的root开始,从上到下从左到右遍历整个树的节点

数和二叉树的区别就是,二叉树只有左右两个节点

广度优先 顺序:A - B - C - D - E - F - G - H - I

代码实现

def breadth_travel(self, root):
        """利用队列实现树的层次遍历"""
        if root == None:
            return
        queue = []
        queue.append(root)
        while queue:
            node = queue.pop()
            print node.elem,
            if node.lchild != None:
                queue.append(node.lchild)
            if node.rchild != None:
                queue.append(node.rchild)
深度优先

深度优先有三种算法:前序遍历,中序遍历,后序遍历

image.png

  • 先序遍历 在先序遍历中,我们先访问根节点,然后递归使用先序遍历访问左子树,再递归使用先序遍历访问右子树
    根节点->左子树->右子树

      #实现 1
      def preorder(self, root):
            """递归实现先序遍历"""
            if root == None:
                return
            print root.elem
            self.preorder(root.lchild)
            self.preorder(root.rchild)
           
      #实现 2  
      def depth_tree(tree_node):
          if tree_node is not None:
              print (tree_node._data)
              if tree_node._left is not None:
                  return depth_tree(tree_node._left)
              if tree_node._right is not None:
                  return depth_tree(tree_node._right)
    
  • 中序遍历 在中序遍历中,我们递归使用中序遍历访问左子树,然后访问根节点,最后再递归使用中序遍历访问右子树
    左子树->根节点->右子树

def inorder(self, root):
      """递归实现中序遍历"""
      if root == None:
          return
      self.inorder(root.lchild)
      print root.elem
      self.inorder(root.rchild) 
  • 后序遍历 在后序遍历中,我们先递归使用后序遍历访问左子树和右子树,最后访问根节点
    左子树->右子树->根节点
def postorder(self, root):
      """递归实现后续遍历"""
      if root == None:
          return
      self.postorder(root.lchild)
      self.postorder(root.rchild)
      print root.elem


转载 原文链接:https://www.jianshu.com/p/ee4cf469f5c4

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/834020.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号