/**
* 113. 路径总和 II
* @author wsq
* @date 2020/09/26
给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
给定如下二叉树,以及目标和 sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
返回:
[
[5,4,11,2],
[5,8,4,5]
]
链接:https://leetcode-cn.com/problems/path-sum-ii
*/
package com.wsq.tree;
import java.util.ArrayList;
import java.util.List;
//Definition for a binary tree node.
class TreeNode {
Integer val;
TreeNode left;
TreeNode right;
TreeNode(Integer x) { val = x; }
}
public class PathSum {
private List<List<Integer>> ansList = new ArrayList();
private List<Integer> pathList = new ArrayList();
/**
* 递归走完每一个分支
* @param root
* @param sum
* @return
*/
public List<List<Integer>> pathSum(TreeNode root, int sum) {
dfs(root, sum);
return ansList;
}
private void dfs(TreeNode root, int sum) {
if(root == null) {
return;
}
// TODO Auto-generated method stub
pathList.add(root.val);
int nextSum = sum - root.val;
if(nextSum == 0 && root.left == null && root.right == null) {
ansList.add(new ArrayList<>(pathList));
}else {
dfs(root.left, nextSum);
dfs(root.right, nextSum);
}
pathList.remove(pathList.size() - 1);
}
/**
* 不是满二叉树,会报错。。。
* @param a
* @param pos
* @return
*/
public static TreeNode buildTree(Integer[] a, int pos) {
if(pos >= a.length || a[pos] == null) {
return null;
}
TreeNode root = new TreeNode(a[pos]);
root.left = buildTree(a, 2 * pos + 1);
root.right = buildTree(a, 2 * pos + 2);
return root;
}
public static void main(String[] args) {
Integer[] a = {1,-2,-3,1,3,-2,null,-1};
TreeNode root = buildTree(a, 0);
int sum = -1;
PathSum ps = new PathSum();
List<List<Integer>> ans = ps.pathSum(root, sum);
for(List<Integer> list: ans) {
for(Integer i: list) {
System.out.print(i + " ");
}
System.out.println();
}
}
}
113. 路径总和 II(递归)
最新推荐文章于 2024-11-12 12:29:51 发布