[LeetCode] 113. Path Sum II

来源:互联网 发布:linux 字符串编码转换 编辑:程序博客网 时间:2024/06/06 14:25

【原题】
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]]

【解释】
给定一颗二叉树和一个目标target,要求返回二叉树中从根节点到叶子结点的所有节点之和为target的路径。

【思路】
DFS的思想,若左右结点都遍历完之后,要将最后一个加入的结点删除,表示已经遍历过该节点所有的左右子女。

public class Solution {    public void pathSumCore(List<List<Integer>> results, List<Integer> result,int sum,TreeNode root){        if(root==null)            return;        result.add(root.val);        if(sum==root.val&&root.left==null&&root.right==null){            results.add(new ArrayList<>(result));            //result.remove(result.size()-1);            //return ;//这里若要返回的话, 必须加前面的删除前面加入的路径        }else{        if(root.left!=null)            pathSumCore(results,result,sum-root.val,root.left);         if(root.right!=null)            pathSumCore(results,result,sum-root.val,root.right);        }        result.remove(result.size()-1);//删除该结点    }     public List<List<Integer>> pathSum(TreeNode root, int sum) {         List<Integer> result=new ArrayList<Integer>();         List<List<Integer>> results=new ArrayList<List<Integer>>();         pathSumCore(results,result,sum,root);         return results;        }}
原创粉丝点击