python求二叉树深度
1.代码实现
class BinaryTreeNode(object):
# 创建二叉树结点的函数
def __init__(self):
self.data = '#'
self.LChild = None
self.RChild = None
class BinaryTree(object):
# 创建二叉树的函数
def CreateBinaryTree(self, Root):
data = input('->')
if data == '#':
Root = None
else:
Root.data = data
Root.LChild = BinaryTreeNode()
self.CreateBinaryTree(Root.LChild)
Root.RChild = BinaryTreeNode()
self.CreateBinaryTree(Root.RChild)
# 求二叉树深度
def maxDepth(self, Root):
if Root.data == '#':
return 0
curLevelNodeList = [Root]
length = 0
while curLevelNodeList:
tempNodeList = []
for node in curLevelNodeList:
if node.LChild is not None:
tempNodeList.append(node.LChild)
if node.RChild is not None:
tempNodeList.append(node.RChild)
curLevelNodeList = tempNodeList
length += 1
return length-1
# 创建一棵二叉树
print('创建一棵二叉树\n')
print(' 4')
print(' / \\')
print(' 5 6')
print(' / \\ \\')
print(' 1 2 7 ')
print('4 5 1 # # 2 # # 6 # 7 # #')
print('请仿照上述序列,输入某一二叉树中各结点的值(#表示空结点),每输入一个值按回车换行:')
bTN = BinaryTreeNode()
bT = BinaryTree()
bT.CreateBinaryTree(bTN)
print(bT.maxDepth(bTN))
2.测试数据及结果
测试数据:1,2,#,#,#
测试结果:2
测试数据:4,5,1,#,#,2,#,#,6,#,7,#,#
测试结果:3