路径总和

解题思路:
递归。找准返回条件以及递归条件。
代码:
/*public class TreeNode
{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x)
{ val = x; }
}*/
public bool HasPathSum(TreeNode root, int sum)
{
if (root == null)
return false;
else
return find(root, sum, 0);
}
public bool find(TreeNode root, int sum, int result)
{
if (root == null && result == sum)
return true;
else if (root != null)
{
result += root.val;
if (root.left != null && root.right == null)
return find(root.left, sum, result);
if (root.right != null && root.left == null)
return find(root.right, sum, result);
else
return find(root.left, sum, result) || find(root.right, sum, result);
}
else return false;
}


被折叠的 条评论
为什么被折叠?



