【LeetCode】Path Sum 解题报告
2017-05-12 12:34
531 查看
【LeetCode】Path Sum 解题报告
标签(空格分隔): LeetCode题目地址:https://leetcode.com/problems/path-sum/#/description
题目描述:
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.
Ways
这个题要背下来!!/** * 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){ return root.val == sum; } return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val); } }
Date
2017 年 5 月 12 日相关文章推荐
- 【LeetCode】112.Path Sum(Easy)解题报告
- Leetcode 64. Minimum Path Sum 最小路径和 解题报告
- [LeetCode]Path Sum,解题报告
- [leetcode] 99. Recover Binary Search Tree 解题报告
- [Leetcode] 306. Additive Number 解题报告
- Leetcode 99. Recover Binary Search Tree 恢复二叉搜索树 解题报告
- 【LeetCode】103. Binary Tree Zigzag Level Order Traversal(Medium)解题报告
- [Leetcode] 179. Largest Number 解题报告
- [Leetcode] 402. Remove K Digits 解题报告
- [Leetcode] 475. Heaters 解题报告
- [Leetcode] 190. Reverse Bits 解题报告
- [Leetcode] 635. Design Log Storage System 解题报告
- 【LeetCode】199.Binary Tree Right Side View(Medium)解题报告
- 【LeetCode】Counting Bits 解题报告
- 【LeetCode】 Add Digits 解题报告
- [leetcode] 271. Encode and Decode Strings 解题报告
- 【LeetCode】513.Find Bottom Left Tree Value(Medium)解题报告
- 【LeetCode】697. Degree of an Array 解题报告
- LeetCode-Ugly Number-解题报告
- leetcode 40. Combination Sum II 解题报告