Path Sum (Java)
2014-12-23 22:02
106 查看
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.
深搜到叶子的和判断与sum是否相等
Source
Test
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.
深搜到叶子的和判断与sum是否相等
Source
public boolean hasPathSum(TreeNode root, int sum) { if( root == null){ return false; } if( root.left == null && root.right == null){ return sum - root.val == 0; } return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val); //递归应当注意的就是状态转移的这个式子,这道题是当前sum确定倒推到叶子所以用减 (通常是叶子确定 推到根用加) }
Test
public static void main(String[] args){ TreeNode a = new TreeNode(5); a.left = new TreeNode(4); a.right = new TreeNode(8); a.left.left = new TreeNode(11); a.left.left.left = new TreeNode(7); a.left.left.right = new TreeNode(2); a.right.left = new TreeNode(13); a.right.right = new TreeNode(4); a.right.right.right = new TreeNode(1); System.out.println(new Solution().hasPathSum(a, 22)); }
相关文章推荐
- [Leetcode] Path Sum II (Java)
- [Leetcode] Binary Tree Maximum Path Sum (Java)
- [Leetcode][JAVA] Path Sum I && II
- Java for LeetCode 124 Binary Tree Maximum Path Sum
- LeetCode详解 之 Path Sum I and II(Java)
- [Leetcode] Minimum Path Sum (Java)
- 【LeetCode-面试算法经典-Java实现】【064-Minimum Path Sum(最小路径和)】
- LeetCode Path Sum II in Java
- Minimum Path Sum (Java)
- [LeetCode][Java] Path Sum II
- LeetCode 64 — Minimum Path Sum(C++ Java Python)
- Path Sum II leetcode java
- Path Sum leetcode java
- Binary Tree Maximum Path Sum (Java)
- Minimum Path Sum java
- leetcode JAVA Minimum Path Sum 难度系数3 3.22
- Path Sum II Java
- Minimum Path Sum leetcode java
- [LeetCode][Java] Minimum Path Sum
- [LeetCode][Java] Binary Tree Maximum Path Sum