开始刷题leetcode day3: Path Sum
来源:互联网 发布:吾爱源码下载 编辑:程序博客网 时间:2024/06/05 18:02
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->2
which sum is 22.
Java
/**
* 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(root.left == null && root.right == null && root.val == sum)
return true;
else
return (hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val));
}
}
注意,用递归
- 开始刷题leetcode day3: Path Sum
- 开始刷题leetcode day3: Majority Element
- 开始刷题 leetcode day39:Minimum Path Sum
- 开始刷题leetcode day3:Factorial Trailing Zeroes
- 开始刷题leetcode day3: Longest Common Prefix
- 开始刷题 leetcode day3: Excel Sheet Column Number
- 开始刷题leetcode day3:Balanced Binary Tree
- 开始刷题leetcode day3:Merge Sorted Array
- 开始刷leetcode day16:Binary Tree Maximum Path Sum
- 开始刷leetcode day3: house robber
- 开始刷leetcode day3:Rotate Array
- [leetcode刷题系列]Path Sum
- [leetcode刷题系列]Path Sum II
- [leetcode刷题系列]Minimum Path Sum
- LeetCode刷题笔录Minimum Path Sum
- LeetCode刷题笔录Path Sum
- LeetCode刷题笔录Path Sum II
- [leetCode刷题笔记]112. Path Sum
- java 资料必备
- oracle集合查询
- poj 1222 Extended lights out (emulator)
- android入门系列之 编译android源代码以及ramdisk.img system.img userdata.img 介绍
- 黑马程序员—C语言—函数小结
- 开始刷题leetcode day3: Path Sum
- VC++动态链接库(DLL)编程深入浅出(zz)
- 延伸的正则表达式
- VolgaCTF2015之lcg的writeup
- 否定先生的第一个CSDN博客
- css 利用table 及 noWrap 实现一列优先使用宽度,另外一列自适应
- linux安装jdk
- 定时任务-quartz的使用,实现可页面化管理
- 根据内核来创建线程--SetThreadAffinityMask函数的使用