LeetCode#112 Path Sum
2015-07-21 20:17
309 查看
Problem Definition:
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example:
Given the below binary tree and
return true, as there exist a root-to-leaf path
Solution: 从根节点开始,减去当前值,往下。
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example:
Given the below binary tree and
sum = 22,
5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1
return true, as there exist a root-to-leaf path
5->4->11->2which sum is 22.
Solution: 从根节点开始,减去当前值,往下。
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param {TreeNode} root # @param {integer} sum # @return {boolean} def hasPathSum(self, root, sum): if root==None: return False if root.val==sum and root.left==None and root.right==None: return True return self.hasPathSum(root.left,sum-root.val)\ or self.hasPathSum(root.right,sum-root.val)
相关文章推荐
- 手机测试项目时报INSTALL_FAILED_INSUFFICIENT_STORAGE
- A Common Data Access Architecture
- 字符串替换
- 树状数组的初次邂逅
- 堆和栈的区别(转过无数次的文章)
- lx-0721-1004汉字统计
- 申请apple 开发者账号所需资料
- document.onmousemove
- bj java 初学2015-07-21
- servlet基础_1
- LeetCode || Search in Rotated Sorted Array II
- mac git 的安装 及实现自动补全
- 三极管深度饱和分析
- CentOS的配置文件
- Apache配置代理的两种方式
- 2015 Multi-University Training Contest 1 Hdu 5297 Y sequence
- Unity3D ParticleSystem粒子系统(3.5版)【初级】
- LeetCode#119 Pascal's Triangle II
- uva 657 The die is cast(双重搜索)
- 数据结构和设计模式05(字符串)