标签:== com after pre 后序遍历 二叉树遍历 [] strong san
二叉树的遍历:
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,‘‘)
标签:== com after pre 后序遍历 二叉树遍历 [] strong san
原文地址:https://www.cnblogs.com/yunxintryyoubest/p/10319404.html