1 题目概述
1.1 题目出处
https://leetcode-cn.com/problems/n-queens/
1.2 题目描述
给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
给定如下二叉树,以及目标和 sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
返回:
[
[5,4,11,2],
[5,8,4,5]
]
2 回溯法
2.1 思想
2.2 代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private List<List<Integer>> resultList = new ArrayList<>();
private List<Integer> tmpList = new ArrayList<>();
public List<List<Integer>> pathSum(TreeNode root, int sum) {
if(root == null){
return resultList;
}
backtrack(sum, 0, root);
return resultList;
}
private void backtrack(int sum, int tmp, TreeNode root){
if(root == null){
// 结束条件
return;
}
tmpList.add(root.val);
if(root.left == null && root.right == null && (tmp + root.val == sum)){
resultList.add(new ArrayList(tmpList));
}else{
// 回溯
backtrack(sum, tmp + root.val, root.left);
backtrack(sum, tmp + root.val, root.right);
}
tmpList.remove(tmpList.size() - 1);
}
}
2.3 时间复杂度
O(N)
2.4 空间复杂度
O(N)