资讯专栏INFORMATION COLUMN

[LeetCode] Path Sum (I & II & III)

张金宝 / 1522人阅读

摘要:

112. Path Sum Problem

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

Note: A leaf is a node with no children.

Example:

Given the below binary tree and sum = 22,

      5
     / 
    4   8
   /   / 
  11  13  4
 /        
7    2      1

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

Solution Recursive
class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if (root == null) return false;
        //has to be a root-to-leaf path
        if (root.val == sum && root.left == null && root.right == null) return true;
        return hasPathSum(root.left, sum-root.val) || hasPathSum(root.right, sum-root.val);
    }
}
Update 2018-11 Solution Iterative
class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if (root == null) return false;
        Deque nodestack = new ArrayDeque<>();
        Deque sumstack = new ArrayDeque<>();
        nodestack.push(root);
        sumstack.push(sum);
        while (!nodestack.isEmpty()) {
            TreeNode curNode = nodestack.pop();
            int curSum = sumstack.pop();
            if (curNode.left == null && curNode.right == null && curNode.val == curSum) return true;
            if (curNode.right != null) {
                nodestack.push(curNode.right);
                sumstack.push(curSum-curNode.val);
            }
            if (curNode.left != null) {
                nodestack.push(curNode.left);
                sumstack.push(curSum-curNode.val);
            }
        }
        return false;
    }
}
Path Sum II Problem

Given a binary tree and a sum, find all root-to-leaf paths where each path"s sum equals the given sum.

Note: A leaf is a node with no children.

Example:

Given the below binary tree and sum = 22,

      5
     / 
    4   8
   /   / 
  11  13  4
 /      / 
7    2  5   1

Return:

[
   [5,4,11,2],
   [5,8,4,5]
]

Solution

class Solution {
    public List> pathSum(TreeNode root, int sum) {
        List> res = new ArrayList<>();
        if (root == null) return res;
        dfs(root, sum, new ArrayList(), res);
        return res;
    }
    private void dfs(TreeNode root, int sum, List temp, List> res) {
        if (sum == root.val && root.left == null && root.right == null) {
            temp.add(root.val);
            List save = new ArrayList<>(temp); //important
            res.add(save);
            temp.remove(temp.size()-1);
        } else {
            temp.add(root.val);
            if (root.left != null) dfs(root.left, sum-root.val, temp, res);
            if (root.right != null) dfs(root.right, sum-root.val, temp, res);
            temp.remove(temp.size()-1);
        }
        
    }
}

Path Sum III Problem

You are given a binary tree in which each node contains an integer value.

Find the number of paths that sum to a given value.

The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).

The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.

Example:

root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8

      10
     /  
    5   -3
   /     
  3   2   11
 /    
3  -2   1

Return 3. The paths that sum to 8 are:

5 -> 3

5 -> 2 -> 1

-3 -> 11

Solution
class Solution {
    public int pathSum(TreeNode root, int sum) {
        if (root == null) return 0;
        return helper(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum);
    }
    private int helper(TreeNode root, int sum) {        
        int count = 0;
        if (sum == root.val) count++;
        if (root.left != null) count += helper(root.left, sum-root.val);
        if (root.right != null) count += helper(root.right, sum-root.val);
        return count;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/77098.html

相关文章

  • [Leetcode] Path Sum I &amp; II &amp; III 路径和1,2,3

    摘要:只要我们能够有一个以某一中间路径和为的哈希表,就可以随时判断某一节点能否和之前路径相加成为目标值。 最新更新请见:https://yanjia.me/zh/2019/01/... Path Sum I Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that addin...

    caiyongji 评论0 收藏0
  • [LintCode/LeetCode] Combination Sum I &amp; II

    摘要:和唯一的不同是组合中不能存在重复的元素,因此,在递归时将初始位即可。 Combination Sum I Problem Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T...

    ThreeWords 评论0 收藏0
  • [Leetcode-Tree] Path Sum I II III

    摘要:解题思路利用递归,对于每个根节点,只要左子树和右子树中有一个满足,就返回每次访问一个节点,就将该节点的作为新的进行下一层的判断。代码解题思路本题的不同点是可以不从开始,不到结束。代码当前节点开始当前节点左节点开始当前节点右节点开始 Path SumGiven a binary tree and a sum, determine if the tree has a root-to-lea...

    notebin 评论0 收藏0
  • [LeetCode] 4Sum &amp; 4Sum II

    摘要:和方法一样,多一个数,故多一层循环。完全一致,不再赘述, 4Sum Problem Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which ...

    sydMobile 评论0 收藏0
  • H-Index &amp; II

    H-Index 题目链接:https://leetcode.com/problems... sort: public class Solution { public int hIndex(int[] citations) { if(citations == null || citations.length == 0) return 0; // sort ...

    mochixuan 评论0 收藏0

发表评论

0条评论

张金宝

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<