classNode(object):def __init__(self, value):
self.value=value
self.left=None
self.right=NoneclassSolution(object):def __init__(self):
root= Node(6)
B= Node(4)
root.left=B
C= Node(7)
root.right=C
D= Node(1)
B.left=D
E= Node(2)
B.right=E
F= Node(3)
C.left=F
G= Node(5)
C.right=G
H= Node(6)
I= Node(8)
D.left=H
E.left=I
self.root=root
self.max_value=0
self.path=[]defmax_depth(self,root):if root ==None:return0if (root.left != None) & (root.right !=None):return max(1 + self.max_depth(root.left), 1 +self.max_depth(root.right))elif (root.left != None) & (root.right ==None):return 1 +self.max_depth(root.left)elif (root.left == None) & (root.right !=None):return 1 +self.max_depth(root.right)else:return 1
defmax_sum(self, root, Sum):if root ==None:returnself.max_valueif (root.left != None) & (root.right !=None):
self.max_sum(root.left, Sum+root.value)
self.max_sum(root.right, Sum+root.value)elif (root.left != None) & (root.right ==None):
self.max_sum(root.left, Sum+root.value)elif (root.left == None) & (root.right !=None):
self.max_sum(root.right, Sum+root.value)else:if (Sum + root.value) >self.max_value:
self.max_value= Sum +root.valuedefFindPath(self, root, expectNumber):
ans= [] #所有路径的集合
if root ==None:returnansdef iterpath(root, expectNumber, dir=[]):if expectNumber >root.value:
dir.append(root.value)#dir保存当前路径(不一定是符合要求的路径)
#分别在左右子树中寻找并更新期望值
if root.left !=None:
iterpath(root.left, expectNumber-root.value, dir)if root.right !=None:
iterpath(root.right, expectNumber-root.value, dir)elif expectNumber ==root.value:
dir.append(root.value)if root.right == None and root.left == None: #如果节点的值与期望值相同,则判断节点是否为叶子结点,如果是叶子结点则是符合条件的路径
tmp =dir[:]
ans.append(tmp)else:
dir.append(0)
dir.pop()#!!!!!!!!!!!!!
iterpath(root, expectNumber)returnansif __name__ == '__main__':
binary_tree=Solution()
max_depth=binary_tree.max_depth(binary_tree.root)
binary_tree.max_sum(binary_tree.root, 0)
path=binary_tree.FindPath(binary_tree.root, binary_tree.max_value)print("二叉树的最大深度(高度)", max_depth)print("从根节点到叶子节点的路径和最大值", binary_tree.max_value)print("从根节点到叶子节点的最大路径", path)