Leetcode Path Sum
2016-07-20 03:38
337 查看
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
Difficulty: Easy
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if(root == null) return false;
if(sum - root.val == 0 && root.left == null && root.right == null) return true;
return (hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val));
}
}
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.
Difficulty: Easy
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if(root == null) return false;
if(sum - root.val == 0 && root.left == null && root.right == null) return true;
return (hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val));
}
}
相关文章推荐
- Leetcode Power of Two/Three/Four
- Leetcode Rotate Image
- 最小边割集
- 云服务器上安装配置Filezilla Server的坑!
- 在安装Ubuntu的MacBook上更改Apple 键盘模式
- 算法日记(Java实现)第20160719(5)期——POJ1008
- 在MacBook Pro 12-1 with ubuntu 15.10 上安装风扇控制器(mbpfan)
- HDU5723 2016 Multi-University Training Contest 1 (最小生成树+dfs)
- 百度地图API 地理位置获取和大头针显示当前位置
- KVM的网络Networking-qemu-kvm和openvswitch原型环境部署和基本测试 (3)
- 创建虚拟机-qemu-kvm和openvswitch原型环境部署和基本测试 (2)
- 基于栈数据结构的算法(poj-布尔表达式)
- git push 提示输入用户名和密码
- qemu-kvm和openvswitch安装部署-qemu-kvm和openvswitch原型环境部署和基本测试 (1)
- Leetcode 33, 81 Search in Rotated Sorted Array I, II
- Android短信发送,监听,及其工具类封装
- HDU 5727 Necklace(玄学+状压DP 或 匈牙利)
- 基本标签
- js window.onload ,$(function(){}) 和script标签 运行规则和错误引起下面的js不能运行 探讨
- as3 中 textfiled的htmltext 的常用属性