Leetcode 112. Path Sum 路径和 解题报告
2016-09-24 13:36
471 查看
1 解题思想
题目意思是给了一个二叉树,每个节点对应一个值,同时给了一个指定的树。然后请问是否有一条从根节点开始,到叶节点的路径,其和正好等于那个值。
做法就是简单的DFS,如果到了叶节点刚好等于那个值就返回True,如果不够或者超过则返回False(搜索的时候如果还没到叶节点就超了,就回溯回去)。
2 原题
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.
3 AC解
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ /** * 直接dfs就好了。。。就是注意下区分根节点和叶节点的定义,我当时都被坑了 * * 叶节点是左右都没有孩子。。我一开始被坑了。。 */ public class Solution { public boolean dfs(TreeNode root,int sum){ if(root==null) return false; sum-=root.val; if(root.left==null && root.right==null) return sum==0; return dfs(root.left,sum) || dfs(root.right,sum); } public boolean hasPathSum(TreeNode root, int sum) { return dfs(root,sum); } }
相关文章推荐
- Leetcode 64. Minimum Path Sum 最小路径和 解题报告
- Leetcode 129. Sum Root to Leaf Numbers 计算路径和 解题报告
- Leetcode 113. Path Sum II 路径和2 解题报告
- Leetcode 63. Unique Paths II 路径搜寻2 解题报告
- Leetcode 124. Binary Tree Maximum Path Sum 最大路径和 解题报告
- Leetcode 71. Simplify Path 简化路径 解题报告
- Leetcode 437. Path Sum III 路径和3 解题报告
- LeetCode解题报告 112. Path Sum [easy]
- [LeetCode] Gray Code 解题报告
- 解题报告-HDOJ-1874(单源最短路径——Dijkstra)
- 解题报告-HDOJ-1874(单源最短路径——SPFA)
- [LeetCode] Longest Common Prefix 解题报告
- [LeetCode] Generate Parentheses 解题报告
- [LeetCode] Jump Game 解题报告
- [LeetCode] Longest Substring Without Repeating Characters 解题报告
- [LeetCode] Largest Rectangle in Histogram 解题报告
- [Leetcode] Length of Last Word 解题报告
- [LeetCode] Insert Interval 解题报告
- [LeetCode] Implement strStr() 解题报告
- [Leetcode] Distinct Subsequences 解题报告