地址:点击打开链接
这道题是实际是遍历树然后求和,只不过加了一个参数,所以要会写BFS和DFS,以及层次遍历
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
return self.DFS(0, sum, root)
def DFS(self, curSum, sum, root):
if root == None:
return False
if root.left == None and root.right == None:
return (root.val + curSum) == sum
return self.DFS(curSum + root.val, sum, root.left) or self.DFS(curSum + root.val, sum, root.right)
自己写了一个深度遍历,不知道对不对
def DFSTree(self, root, nodeList):
if root == None:
return None
if root.left == None and root.right == None:
nodeList.append(root.val)
else:
nodeList.extend(self.DFSTree(root.left))
nodeList.extend(self.DFSTree(root.right))
return nodeList