首页 > 代码库 > 113. Path Sum II

113. 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]]

理解下leaf node:先序遍历,先加root,然后遍历左右子树,如果都为null(遍历完),回溯。
4
/ \
null null
/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public List<List<Integer>> pathSum(TreeNode root, int sum) {        List<List<Integer>> res=new ArrayList<>();        List<Integer> check=new ArrayList<Integer>();        dps(root,res,check,sum);        return res;    }    public void dps(TreeNode root, List<List<Integer>> res,List<Integer> check,int sum)    {        if(root==null)        {            return;        }         check.add(root.val);        if(root.left==null&&root.right==null&&sum==root.val)        {                res.add(new ArrayList<>(check));        }        else        {        dps(root.left,res,check,sum-root.val);        dps(root.right,res,check,sum-root.val);        }        check.remove(check.size()-1);    }            }

 

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public List<List<Integer>> pathSum(TreeNode root, int sum) {        List<List<Integer>> res=new ArrayList<>();        List<Integer> check=new ArrayList<Integer>();        dps(root,res,check,sum);        return res;    }    public void dps(TreeNode root, List<List<Integer>> res,List<Integer> check,int sum)    {        if(root==null)        {            return;        }        if(root.left==null&&root.right==null)        {            if(sum==root.val)            {                   List<Integer> tmp=new ArrayList<>(check);                tmp.add(root.val);                res.add(tmp);            }            return;        }        check.add(root.val);        dps(root.left,res,check,sum-root.val);        dps(root.right,res,check,sum-root.val);        check.remove(check.size()-1);    }            }

 

113. Path Sum II