1. 程式人生 > >【Leetcode】113Path Sum II

【Leetcode】113Path Sum II

imp col public 集合 註意 integer print body 元素

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

Tips:在112題的基礎上,加深難度,本題要求輸出和為sum的樹中的所有路徑。

本題要註意List<Integer> 是 List<List<Integer>> 的一個元素。要求出所有路徑,需要每找到一條List<Integer>類型的路徑,就將其添加到 List<List<Integer>>集合中。

package medium;

import java.util.ArrayList;
import java.util.List;

public class L113PathSumII {
    public List<List<Integer>> pathSum(TreeNode root, int
sum) { List<List<Integer>> path = new ArrayList<>(); List<Integer> oneline = new ArrayList<>(); if (root == null) return path; int ans = 0; hasPathSumCore(root, sum, path, ans,oneline); return path; }
private List<List<Integer>> hasPathSumCore(TreeNode root, int sum, List<List<Integer>> path, int ans,List<Integer> oneline) { ans += root.val; oneline.add(root.val); if (ans == sum && root.left == null && root.right == null) { path.add(new ArrayList<Integer>(oneline)); } if (root.left != null) { hasPathSumCore(root.left, sum,path, ans,oneline); } if (root.right != null) { hasPathSumCore(root.right, sum,path, ans,oneline); } ans -= root.val; oneline.remove(oneline.size()-1); return path; } public static void main(String[] args) { TreeNode root = new TreeNode(5); TreeNode node1 = new TreeNode(4); TreeNode node2 = new TreeNode(8); TreeNode node3 = new TreeNode(11); TreeNode node4 = new TreeNode(13); TreeNode node5 = new TreeNode(4); TreeNode node6 = new TreeNode(7); TreeNode node7 = new TreeNode(2); TreeNode node8 = new TreeNode(1); root.left = node1; root.right = node2; node1.left = node3; node2.left = node4; node2.right = node5; node3.left = node6; node3.right = node7; node5.right = node8; node1.right = null; node6.left = null; node6.right = null; node7.left = null; node7.right = null; node4.left = null; node4.right = null; node5.left = null; node8.left = null; node8.right = null; int sum = 22; L113PathSumII l113 = new L113PathSumII(); List<List<Integer>> ans =new ArrayList(); ans=l113.pathSum(root, sum); for(int i=0;i<ans.size();i++){ List<Integer> iter=ans.get(i); for(int j=0;j<iter.size();j++){ System.out.println(iter.get(j)); } } System.out.println("HHHHHHHHHHHHH"); TreeNode root1 = new TreeNode(-2); TreeNode root2 = new TreeNode(-3); root1.left = null; root1.right = root2; root2.left = null; root2.right = null; ans=l113.pathSum(root1, -5); for(int i=0;i<ans.size();i++){ List<Integer> iter=ans.get(i); for(int j=0;j<iter.size();j++){ System.out.println(iter.get(j)); } } } }

【Leetcode】113Path Sum II