给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。
说明: 叶子节点是指没有子节点的节点。
示例:
给定如下二叉树,以及目标和 sum = 22
,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
返回 true
, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2
。
解题思路
这个问题太简单了,我们只要搞清楚什么时候才是叶子节点,这个问题就解决了。当node.left==None and node.right==None
的时候,node
就是叶子节点
。
class Solution:
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
if not root:
return False
if not (root.left or root.right):
return sum == root.val
return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)
同样的,我们看看通过迭代怎么解决这个问题?无非是通过非递归遍历来解决这个问题。
Leetcode 144:二叉树的前序遍历(最优雅的解法!!!)
Leetcode 94:二叉树的中序遍历(最优雅的解法!!!)
Leetcode 145:二叉树的后序遍历(最详细的解法!!!)
Leetcode 102:二叉树的层次遍历(最详细解决方案!!!)
我这里通过前序遍历来解决,大家可以尝试通过中序和后序来解决。
class Solution:
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
stack = [(root, root.val)]
while stack:
node, t = stack.pop()
if not (node.left or node.right) and val == sum:
return True
if node.right:
stack.append((node.right, val + node.right.val))
if node.left:
stack.append((node.left, val + node.left.val))
return False
我将该问题的其他语言版本添加到了我的GitHub Leetcode
如有问题,希望大家指出!!!