class Node(object):
def __init__(self,elem=None,lchild=None,rchild=None):
self.elem=elem
self.lchild=lchild
self.rchild=rchild
class Tree(object):
def __init__(self,root=None):
self.root=root
def add(self,elem):
node=Node(elem)
if self.root==None:
self.root=node
else:
queue=list()
queue.append(self.root)
while queue:
cur=queue.pop(0)
if cur.lchild==None:
cur.lchild=node
return
elif cur.rchild==None:
cur.rchild=node
return
else:
queue.append(cur.lchild)
queue.append(cur.rchild)
def pre_order(self,root):
if root==None:
return
print(root.elem)
self.pre_order(root.lchild)
self.pre_order(root.rchild)
def mid_order(self,root):
if root==None:
return
self.mid_order(root.lchild)
print(root.elem)
self.mid_order(root.rchild)
def post_order(self,root):
if root==None:
return
self.post_order(root.lchild)
self.post_order(root.rchild)
print(root.elem)
def maxDepth1(self,root):
if root==None:
return 0
cur=[]
cur.append(root)
length=0
while len(cur)!=0:
temp=[]
for node in cur:
if node.lchild!=None:
temp.append(node.lchild)
if node.rchild!=None:
temp.append(node.rchild)
cur=temp
length+=1
return length
def maxDepth2(self,root):
if root==None:
return 0
return max(self.maxDepth2(root.lchild),self.maxDepth2(root.rchild))+1
def DFS(self,root):
if root==None:
return
stack=[]
stack.append(root)
while stack:
cur=stack.pop()
print(cur.elem,end=" ")
if cur.rchild!=None:
stack.append(cur.rchild)
if cur.lchild!=None:
stack.append(cur.lchild)
def BFS(self,root):
if root==None:
return
queue=[]
queue.append(root)
while queue:
cur=queue.pop(0)
print(cur.elem,end=" ")
if cur.rchild!=None:
queue.append(cur.rchild)
if cur.lchild!=None:
queue.append(cur.lchild)
if __name__=='__main__':
tree=Tree()
tree.add('A')
tree.add('B')
tree.add('C')
tree.add('D')
tree.add('E')
tree.add('F')
tree.add('G')
tree.pre_order(tree.root)
print("深度(层序遍历)",tree.maxDepth1(tree.root))
print("深度(递归)", tree.maxDepth2(tree.root))
tree.DFS(tree.root)
print()
tree.BFS(tree.root)