首页 > 其他 > 详细

二叉树遍历

时间:2019-01-25 14:44:13      阅读:174      评论:0      收藏:0      [点我收藏+]

二叉树的遍历:

class Tree():
def __init__(self, val):
self.val = val
self.left, self.right = None, None

root = Tree(2)
root.right = Tree(10)
root.right.left = Tree(20)
root.left = Tree(5)
root.left.right = Tree(19)
root.left.left = Tree(9)



前序遍历:根节点,左节点,右节点
class BeforeTravel():
def __init__(self):
self.list = []

def Before(self, root):
if root:
self.list.append(root.val)
self.Before(root.left)
self.Before(root.right)
return self.list
res = BeforeTravel().Before(root)


中序遍历:左节点,根节点,右节点
class MiddleTravel():
def __init__(self):
self.list = []

def Middle(self, root):
if root:
self.Middle(root.left) ##当递归到最底部的时候,在倒回去执行
self.list.append(root.val)
self.Middle(root.right) ##当左节点下面有右节点的时候,上面的递归会一直到上面的根节点(存在右节点的时候),在往下面找左边的右边的节点
return self.list
res = MiddleTravel().Middle(root)


后序遍历:左节点,右节点,根节点
class AfterTravel():
def __init__(self):
self.list = []

def After(self, root):
if root:
self.After(root.left)
self.After(root.right)
self.list.append(root.val)
return self.list
res = AfterTravel().After(root)
# print(res)



找到二叉树所有的路径和:
class   all_route():
def __init__(self):
self.list=[]
def all(self,root,ele):
if root:
ele+=str(root.val)
if root.left==None and root.right==None:
self.list.append(ele)
print(self.list)
if root.left:
self.all(root.left,ele+‘->‘)
if root.right:
self.all(root.right,ele+‘->‘)
all_route().all(root,‘‘)

 

二叉树遍历

原文:https://www.cnblogs.com/yunxintryyoubest/p/10319404.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!