《树》112. 路径总和《leetcode》

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);
    }
}

再提一点:

优雅的代码。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值