class Node(object):
def __init__(self,elem):
self.elem=elem
self.lchild=None
self.rchild=None
class Tree(object):
def __init__(self):
self.root=None
def add(self,elem):#二叉树,添加一个元素
node=Node(elem=elem)
if self.root is None:
self.root=node
return
queue=[self.root]
while queue:
cur_node=queue.pop(0)
if cur_node.lchild is None:
cur_node.lchild=node
return
else:
queue.append(cur_node.lchild)
if cur_node.rchild is None:
cur_node.rchild=node
return
else:
queue.append(cur_node.rchild)
def preorder(self,node): #根左右,递归
if node is None:
return
print(node.elem,end=' ')
self.preorder(node.lchild)
self.preorder(node.rchild)
# 先序打印二叉树(非递归)
def preOrderTraverse(self,node):
stack = [node]
while stack:
node = stack.pop()
print(node.elem,end=' ')
if node.rchild is not None:
stack.append(node.rchild)
if node.lchild is not None:
stack.append(node.lchild)
def inorder(self,node):#左根右,递归
if node is None:
return
self.inorder(node.lchild)
print(node.elem,end=' ')
self.inorder(node.rchild)
def postorder(self,node):#左根右,递归
if node is None:
return
self.postorder(node.lchild)
self.postorder(node.rchild)
print(node.elem,end=' ')
# 求二叉树节点个数
def treeNodenums(self,node):
if node is None:
return 0
nums = self.treeNodenums(node.lchild)
nums += self.treeNodenums(node.rchild)
return nums + 1
# 二叉树的最大深度
def bTreeDepth(self,node):
if node is None:
return 0
ldepth = bTreeDepth(node.lchild)
rdepth = bTreeDepth(node.rchild)
return (max(ldepth, rdepth) + 1)
if __name__ == '__main__':
tree=Tree()
for i in range(10):
tree.add(i)
tree.postorder(tree.root)
print('\n')
tree_nums=tree.treeNodenums(tree.root)
print(tree_nums)