[Leetcode]Path Sum&Path Sum II

来源:互联网 发布:阿里云 盘古 编辑:程序博客网 时间:2024/06/06 13:07

Path Sum


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.

For 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.


最简单的递归题

public boolean hasPathSum(TreeNode root, int sum) {        if (root == null) return false;        if (root.left == null && root.right == null && root.val == sum) {            return true;        }        return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);    }


Path Sum II


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

For 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]]

两道题思路是一样一样的,都是利用dfs自顶向下搜索。不同的事这里需要维护一个结果集,因此需要在每次递归中加入正在递归的节点,如果该节点的值正好等于我们需要的sum并且是叶子结点,那说明找到了一种方案,将此方案加入结果集中。如果还有左右子节点,则递归遍历这些节点,如不符合即返回并从结果中删去这个遍历过的节点。

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

这里值得一提的是这个问题和 Triangle问题有点相似,都是求自顶向下的路径和。但是triangle问题给的是结构化的一个三角形,并且求的是最小路径和,所以用dp填表法来做。

0 0