LeetCode 112 Path Sum
2015-11-27 10:59
411 查看
题目描述
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,
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
代码
[code] static boolean hasPath; public static boolean hasPathSum(TreeNode root, int sum) { if (root == null) { return false; } hasPath = false; help(root, 0, sum); return hasPath; } static void help(TreeNode node, int cur, int sum) { cur += node.val; boolean isLeaf = (node.left == null) && (node.right == null); if (cur == sum && isLeaf) { hasPath = true; } if (node.left != null) { help(node.left, cur, sum); } if (node.right != null) { help(node.right, cur, sum); } cur -= node.val; }
更简洁的代码:
[code] public static boolean hasPathSum2(TreeNode root, int sum) { if (root == null) { return false; } if (root.left == null && root.right == null) { return root.val == sum; } return (root.left != null && hasPathSum2(root.left, sum - root.val)) || (root.right != null && hasPathSum2(root.right, sum - root.val)); }
相关文章推荐
- Android分享功能源码解读
- 在 Windows 環境下利用 VNC 遠端控管 Mac OS X Server
- 传值和传引用
- NLP 数据集整理(持续更新。。。)
- find命令相关使用方法
- Bugtags奉命解救宝贵的双手,务必将此文章转给你身边的程序猿
- 对HTML6的未来有何感想
- NSIS 使用SendMessage环境变量不能立即生效解决办法(进程中无效)
- 南大软院大神养成计划——第十二天
- 三、Camera显示之Hal层的适配(一)
- 显示器的分辨率被锁定的可选解决方案
- 值类型和引用类型
- VM11下安装RHEL7.1
- centos 安装配置 nexus maven私有仓库
- Linux下特殊权限suid和set_gid权限
- nginx编译增加其他模块
- Java基础之深入理解泛型
- Android创建桌面快捷方式几种方法
- HashMap解决hash冲突的方法
- 贪吃蛇