今天正好师弟在做这道题,我也就跟着做了。
题目描述:给定一个二叉树和一个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));
}
}
}
递归还有很多要学习。