112. Path Sum && 113. Path Sum II

来源:互联网 发布:windows邮件服务器搭建 编辑:程序博客网 时间:2024/05/11 23:32

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.

都是用dfs解决,不同的是112只要求判断是否存在path sum,113要求返回所有可能的path sum。

public class Solution {    public boolean hasPathSum(TreeNode root, int sum) {        if(root == null ) return false;        return hasPath(root, sum);    }     public boolean hasPath(TreeNode root, int sum){        if(root.left == null && root.right == null && root.val == sum) return true;  //叶子节点        if(root.left != null && hasPath(root.left,sum-root.val))return true;        if(root.right != null && hasPath(root.right,sum-root.val))return true;        return false;     }}
public class Solution {    List<List<Integer>> r = new ArrayList<List<Integer>>();    public List<List<Integer>> pathSum(TreeNode root, int sum) {        if(root == null ) return r;        List<Integer> tmp = new ArrayList<Integer>();        hasPath(root, sum,tmp);        return r;    }     public void hasPath(TreeNode root, int sum , List<Integer> tmp){        if(root.left == null && root.right == null && root.val == sum) {   //叶子节点            tmp.add(root.val);            r.add(new ArrayList<Integer>(tmp));            tmp.remove(tmp.size()-1);            return;        };        tmp.add(root.val);                                                 //dfs        if(root.left != null){            hasPath(root.left, sum-root.val , tmp);        }        if(root.right != null){           hasPath(root.right, sum-root.val , tmp);        }        tmp.remove(tmp.size()-1);     }}
0 0