leetcode:leetcode :Path Sum
2014-06-11 21:20
155 查看
题目的意思是给出一个二叉树,询问是否存在从根节点到叶子节点的路径,路径上的节点的和等于给出的数值。
直接遍历就可以了。
直接遍历就可以了。
<span style="font-size:18px;">/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { static int ans = 0; // static int sum = 0; static boolean flag = false; public boolean hasPathSum(TreeNode root, int sum) { ans = 0; flag = false; traverl(root, sum); return flag; } public static boolean isLeaf(TreeNode root){ return root.left == null && root.right == null; } public static void traverl(TreeNode root, int sum){ if(root != null && !flag){ ans += root.val; if(isLeaf(root) && sum == ans){ flag = true; } traverl(root.left, sum); traverl(root.right, sum); ans -= root.val; } } } </span>
相关文章推荐
- LeetCode : Path Sum
- 【LeetCode从零单排】No112 Path Sum
- LeetCode Path Sum
- leetcode 64. Minimum Path Sum
- LeetCode 112. Path Sum
- (Leetcode)64. Minimum Path Sum(medium)
- LeetCode | Path Sum
- 【Leetcode】Path Sum
- [leetcode 112]Path Sum
- leetcode 64. Minimum Path Sum-最小路径和|动态规划
- 【leetcode】Path Sum
- LeetCOde 64. Minimum Path Sum
- leetcode 112. Path Sum
- LeetCode 112 Path Sum
- [勇者闯LeetCode] 112. Path Sum
- LeetCode 112 Path Sum
- [Leetcode]Path Sum
- LeetCode112 Path Sum
- leetcode 89: Path Sum
- [LeetCode] Path Sum