您的位置:首页 > 其它

LeetCode:Path Sum

2014-12-10 21:25 309 查看
今天正好师弟在做这道题,我也就跟着做了。

题目描述:给定一个二叉树和一个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));
}

}
}


递归还有很多要学习。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: