LeetCode:Path Sum
2014-12-10 21:25
309 查看
今天正好师弟在做这道题,我也就跟着做了。
题目描述:给定一个二叉树和一个int型的数字,判断是否存在一条从根节点到叶子节点的路径使得该路径上各节点之和等于该数字。
Tip:递归实现
递归还有很多要学习。
题目描述:给定一个二叉树和一个int型的数字,判断是否存在一条从根节点到叶子节点的路径使得该路径上各节点之和等于该数字。
Tip:递归实现
/** * Definition for binary tree * 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) { if(root.val == sum) return true; else return false; } else { if(root.left!=null && root.right!=null) { return(hasPathSum(root.left, sum-root.val)||hasPathSum(root.right, sum-root.val)); } else if(root.left!=null) return(hasPathSum(root.left, sum-root.val)); else return(hasPathSum(root.right, sum-root.val)); } } }
递归还有很多要学习。
相关文章推荐
- [Leetcode] Path Sum
- Leetcode--Path Sum
- LeetCode: Path Sum
- LeetCode——Path Sum
- 【Leetcode】64. Minimum Path Sum
- LeetCode 112:Path Sum
- LeetCode : Path Sum
- LeetCode 64. Minimum Path Sum
- [Leetcode] Path Sum路径和
- [LeetCode] Path Sum
- 【Leetcode】【python】Path Sum
- LeetCode: Path Sum
- leetcode - Path Sum
- 【leetcode c++】 112 Path Sum
- leetcode 64. Minimum Path Sum
- [leetcode]Path Sum (分支求和 C语言)
- leetcode_题解_path sum_easy
- [LeetCode] Path Sum
- [LeetCode] 112. Path Sum
- [LeetCode]Path Sum