112. Path Sum
2016-06-09 22:38
190 查看
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
DFS模板题。注意节点数值可能为负数,常用的sum>target的剪枝不能用了,老老实实搜吧。
要求里面是从根到【叶子】节点,所以不满足此条件的和等于sum也不能算。
public boolean hasPathSum(TreeNode root, int sum)
{
if(root==null)
return false;
return dfs(root, 0, sum);
}
private boolean dfs(TreeNode t,int sum,int target)
{
int val=sum+t.val;
if(val==target&&t.left==null&&t.right==null)
return true;
if(t.left!=null)
if(dfs(t.left, val, target))
return true;
if(t.right!=null)
if(dfs(t.right, val, target))
return true;
return false;
}
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.
DFS模板题。注意节点数值可能为负数,常用的sum>target的剪枝不能用了,老老实实搜吧。
要求里面是从根到【叶子】节点,所以不满足此条件的和等于sum也不能算。
public boolean hasPathSum(TreeNode root, int sum)
{
if(root==null)
return false;
return dfs(root, 0, sum);
}
private boolean dfs(TreeNode t,int sum,int target)
{
int val=sum+t.val;
if(val==target&&t.left==null&&t.right==null)
return true;
if(t.left!=null)
if(dfs(t.left, val, target))
return true;
if(t.right!=null)
if(dfs(t.right, val, target))
return true;
return false;
}
相关文章推荐
- 文件压缩与解压
- jQuery实现<textarea>高度自适应,适用于td中的textarea
- iOS 限制输入字数完美解决方案
- 111. Minimum Depth of Binary Tree
- Java序列化与反序列化
- 深入理解CSS中的定位(position)
- 一个关于JS作用域链的例子
- 一个web项目web.xml的配置中<context-param>配置作用
- POJ1503
- C++ sizeof关键字的使用总结
- c++点滴
- C++走向远洋——67(项目二、洗牌)
- ajax笔记
- LeetCode:Combination Sum III
- 110. Balanced Binary Tree
- 《JavaScript学习笔记》:第一个面向对象的程序
- C++复习1.const用法
- poj3281Dining
- android ui 练习
- WindowsServer2012 搭建多台Tomcat