112. 路径总和
难度简单467
给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。
说明: 叶子节点是指没有子节点的节点。
示例:
给定如下二叉树,以及目标和 sum = 22
,
5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1
返回 true
, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2
。
思路解析:
dfs。
AC代码1:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean re=false;
public int Sum=0;
public void dfs(TreeNode root,int tSum)
{
if(root==null)//防止出现空指针
return;
if(root.left==null&&root.right==null)//叶子节点
{
//System.out.println(root.val);
//System.out.println(tSum+" "+Sum);
if(tSum+root.val==Sum)
re=true;
return;
}
if(re)//加快进程。 只要有一组就返回true;
return;
//System.out.println(tSum);
dfs(root.left, tSum+root.val);
dfs(root.right, tSum+root.val);
return;
}
public boolean hasPathSum(TreeNode root, int sum) {
Sum=sum;
re=false;
dfs(root,0);
return re;
}
}
AC代码2:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) {
return false;
}
if (root.left == null && root.right == null) {
return sum - root.val == 0;
}
return hasPathSum(root.left, sum - root.val)
|| hasPathSum(root.right, sum - root.val);
}
}
再提一点:
优雅的代码。