python中遍历树的方法有哪些

  介绍

这篇文章主要介绍了python中遍历树的方法有哪些,具有一定借鉴价值,需要的朋友可以参考下。希望大家阅读完这篇文章后大有收获。下面让小编带着大家一起了解一下。

<强>各种遍历顺序如下图所示:

 python中遍历树的方法有哪些

<强>树的最大深度,

#,class  TreeNode(对象):   #,,,,,def  __init__(自我,,x):   #,,,,,,,,,self.val =, x   #,,,,,,,,,self.left =,没有   #,,,,,,,,,self.right =,没有   class 解决方案(对象):   ,,,def  maxdepth(自我,,根):   ,,,,,,,if  root  is 没有:   ,,,,,,,,,,,return  0   ,,,,,,,return 马克斯(self.maxdepth (root.left), self.maxdepth (root.right)) + 1

<强>深度优先

深度优先遍历有三种方式:前序遍历,中序遍历和后序遍历

所说的前序,中序,后序,是指根节点的先后顺序。

前序遍历:根节点→左子树→右子树

#,class  TreeNode(对象):   #,,,,,def  __init__(自我,,x):   #,,,,,,,,,self.val =, x   #,,,,,,,,,self.left =,没有   #,,,,,,,,,self.right =,没有   class 解决方案(对象):   ,,,def 预订(自我,,根):   ,,,,,,,if  root  is 没有:   ,,,,,,,,,,,return  & # 39; & # 39;   ,,,,,,,print  root.val   ,,,,,,,if  root.lef:   ,,,,,,,,,,,self.preorder (root.left)   ,,,,,,,if  root.right:   ,,,,,,,,,,,self.preorder (root.right)

中序遍历:左子树→根节点→右子树

#,class  TreeNode(对象):   #,,,,,def  __init__(自我,,x):   #,,,,,,,,,self.val =, x   #,,,,,,,,,self.left =,没有   #,,,,,,,,,self.right =,没有   class 解决方案(对象):   ,,,def  midorder(自我,,根):   ,,,,,,,if  root  is 没有:   ,,,,,,,,,,,return  & # 39; & # 39;   ,,,,,,,if  root.lef:   ,,,,,,,,,,,self.midorder (root.left)   ,,,,,,,print  root.val   ,,,,,,,if  root.right:   ,,,,,,,,,,,self.midorder (root.right)

后序遍历:左子树→右子树→根节点

#,class  TreeNode(对象):   #,,,,,def  __init__(自我,,x):   #,,,,,,,,,self.val =, x   #,,,,,,,,,self.left =,没有   #,,,,,,,,,self.right =,没有   class 解决方案(对象):   ,,,def  endorder(自我,,根):   ,,,,,,,if  root  is 没有:   ,,,,,,,,,,,return  & # 39; & # 39;   ,,,,,,,if  root.lef:   ,,,,,,,,,,,self.endorder (root.left)   ,,,,,,,if  root.right:   ,,,,,,,,,,,self.endorder (root.right)   ,,,,,,,print 根。val

<>强广度优先

广度优先遍历,即层次遍历,优先遍历兄弟节点

层次遍历:根节点→左节点→右节点

#,class  TreeNode(对象):   #,,,,,def  __init__(自我,,x):   #,,,,,,,,,self.val =, x   #,,,,,,,,,self.left =,没有   #,,,,,,,,,self.right =,没有   class 解决方案(对象):   def  graorder(自我,,根):   if  root  is 没有:   return  & # 39; & # 39;   queue =,(根)   while 队列:   时间=res  []   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null

python中遍历树的方法有哪些