tree 112_113_437

112. Path Sum

给一颗二叉树和一个数,如果有一条从根到叶子结点和等于sum的的路径就返回true。

非常简单,不说了:

int res = 0;
public boolean hasPathSum(TreeNode root, int sum) {
    if (root == null) return false;

    if (root.left == null && root.right == null && res + root.val == sum)
        return true;

    res += root.val;
    boolean a = hasPathSum(root.left, sum) || hasPathSum(root.right, sum);
    res -= root.val;
    return a;
}

113. Path Sum II

和上题几乎一样,只不过要返回所有等于sum的路径。

也不说了:

public List<List<Integer>> pathSum(TreeNode root, int sum) {
    List<List<Integer>> res = new ArrayList<>();
    helper(root, sum, res, new ArrayList<>(), 0);
    return res;
}

public void helper(TreeNode root, int sum, List<List<Integer>> res, List<Integer> once, int path) {
    if (root == null) return;
    if (root.left == null && root.right == null && root.val + path == sum) {
        once.add(root.val);
        res.add(new ArrayList<>(once));
        once.remove(once.size()-1);
        return;
    }

    once.add(root.val);
    helper(root.left, sum, res, once, path+root.val);
    helper(root.right, sum, res, once, path+root.val);
    once.remove(once.size()-1);
}

437. Path Sum III

这题也是找到有多少条路径和等于sum的路径,但是不是从根结点到叶子结点了,而是树中任意的起始结点和任意的结束结点。

终于有点难度了,首先可以暴力求解,就是遍历整棵树,每遍历到一个结点时就求一下以该结点为根结点的树有几条路径。

但是当然不能用这么笨的方法了:

  1. 可以创建一个hashmap,存储每个根结点到当前结点的路径和temp
  2. 例如遍历到当前结点为i,路径和为temp
  3. 然后看一下map中有没有值等于 temp - sum的键值对,比如说有的话,设为j,即从根结点到j结点的路径和为temp - sum,那么说明从j结点到i结点的路径和就是temp - (temp - sum)= sum,那么一遍前序遍历就可以得到结果了。
  4. 时间复杂度:O(n)
  5. 空间复杂度:O(n)
public int pathSum(TreeNode root, int sum) {
    //初始值
    map.put(0, 1);
    helper(root, sum, 0);
    return res;
}

HashMap<Integer, Integer> map = new HashMap<>();
int res = 0;
public void helper(TreeNode root, int sum, int path) {
    if (root == null) return;

    int temp = path + root.val;
    if (map.containsKey(temp - sum)) {
        res += map.get(temp - sum);
    }
    if (!map.containsKey(temp))
        map.put(temp, 0);
    
    map.put(temp, map.get(temp)+1);
    helper(root.left, sum, path+root.val);
    helper(root.right, sum, path+root.val);
    map.put(temp, map.get(temp)-1);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值