113. Path Sum II
Posted Machelsky
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章