LeetCode 112 Path Sum
来源:互联网 发布:中频治疗仪 知乎 编辑:程序博客网 时间:2024/05/18 05:20
题目描述
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.
代码
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; }
更简洁的代码:
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)); }
1 0
- LeetCode(112)Path Sum
- LeetCode 112 Path Sum
- LeetCode: Path Sum [112]
- LeetCode 112 Path Sum
- [leetcode 112] Path Sum
- leetCode #112 path sum
- [LeetCode 112]Path Sum
- leetcode || 112、Path Sum
- LeetCode 112: Path Sum
- LeetCode 112 Path Sum
- leetcode[112]:Path Sum
- leetcode-112-Path Sum
- Leetcode# 112 Path Sum
- leetcode 112: Path Sum
- LeetCode 112: Path Sum
- [leetcode 112]Path Sum
- LeetCode 112 Path Sum
- LeetCode 112:Path Sum
- 非安装的tomcat,如何注册成系统服务
- Task,Thread ,ThreadPool。
- R语言——3
- SharedPreferences存取对象
- <15> go string_formatting
- LeetCode 112 Path Sum
- Android分享功能源码解读
- asp.net执行alter
- 欢迎使用CSDN-markdown编辑器
- JAVA23种设计模式
- 网上办公室-Tower
- iOS 单元测试之XCTest详解(一),iosxctest
- android java写布局LinearLayou.LayoutParams参数
- 利用swipelistview完成qq聊天列表右滑删除功能