当前位置: 首页 > 后端技术 > Python

Python详细实现树的深度优先遍历和广度优先遍历

时间:2023-03-26 11:25:13 Python

本文介绍python实现树的深度优先遍历和广度优先遍历。分享给大家,供大家参考。下面的数和二叉树的具体区别在于,二叉树只有左右两个节点的广度优先级顺序为:A-B-C-D-E-F-G-H-I根):”""使用队列实现分层树遍历"""ifroot==None:returnqueue=[]queue.append(root)whilequeue:node=queue.pop(0)printnode.elem,ifnode.lchild!=None:queue.append(node.lchild)ifnode.rchild!=None:queue.append(node.rchild)depth-firstdepth-first共有三种算法:前序遍历,中序遍历,后序遍历根节点->左子树->右子树implement1defpreorder(self,root):"""递归实现前序遍历"""ifroot==None:returnprintroot.elemself.preorder(root.lchild)self.preorder(root.rchild)implements2defdepth_tree(tree_node):iftree_nodeisnotNone:print(tree_node._data)iftree_node._leftisnoeNone:returndepth_tree(tree_node._left)iftree_node._rightisnotNone:return深度树(tree_node._right)中序遍历在中序遍历中,我们递归使用中序遍历访问左子树,然后访问根节点,最后使用中序遍历访问右子树leftsubtree->根节点->右子树definorder(self,root):"""中序遍历的递归实现"""ifroot==None:returnself.inorder(root.lchild)printroot.elemself.inorder(root.rchild)后序遍历在后序遍历中,我们递归地使用后序遍历顺序遍历访问左子树和右子树,最后访问根节点外汇术语解释http://www.fx61.com/definitions左子树->右子树->根节点defpostorder(self,root):"""递归实现后续遍历"""ifroot==None:returnself.postorder(root.lchild)self.postorder(root.rchild)printroot.elem