classSolution(object):deffindBottomLeftValue(self, root):"""
:type root: TreeNode
:rtype: int
"""
res = self.Traversal(root)return res[1]defTraversal(self, root):if root isNone:return[0,0]if root.left isNoneand root.right isNone:return[1, root.val]
left = self.Traversal(root.left)
right = self.Traversal(root.right)
current = left if left[0]>=right[0]else right
current[0]+=1return current
路径总和 (LC 112) 搜索单条路径,使用后序遍历立即返回模式
题目思路:
代码实现:
classSolution(object):defhasPathSum(self, root, targetSum):"""
:type root: TreeNode
:type targetSum: int
:rtype: bool
"""if root isNone:returnFalse
res = self.traversal(root, targetSum-root.val)return res
deftraversal(self, node, count):# 遇到叶子节点if node.left isNoneand node.right isNone:if count ==0:returnTrueelse:returnFalseif node.left isnotNone:
count -= node.left.val
left = self.traversal(node.left,count)
count += node.left.val
if left:returnTrueif node.right isnotNone:
count -= node.right.val
right = self.traversal(node.right, count)
count += node.right.val
if right:returnTruereturnFalse