Uno, Título Descripción
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
Note: A leaf is a node with no children.
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]
]
, La solución segundo problema
Método uno: retroceso
El título sobre la base de la suma de la ruta requiere devuelve el método específicas ruta calificado. Pero la rutina es la misma.
- condición final :
- Cuando los nodos hoja atravesados, podemos determinar si o no la suma acumulativa actual es igual al objetivo cur.
- Recursiva dejó constantemente subárbol, cuando el extremo del subárbol izquierdo de forma recursiva, volverá cerca del suelo, por lo que ¿hacia dónde vamos hacia atrás, el camino último valor eliminado.
List<List<Integer>> paths = null;
List<Integer> path = null;
int sum = 0;
public List<List<Integer>> pathSum(TreeNode root, int target) {
paths = new LinkedList<>();
if (root == null)
return paths;
path = new ArrayList<>();
sum = target;
dfs(root, root.val);
return paths;
}
private void dfs(TreeNode root, int cur) {
path.add(root.val);
if (root.left == null && root.right == null && cur == sum) {
paths.add(new ArrayList<>(path));
return;
}
if (root.left != null) {
dfs(root.left, cur + root.left.val);
path.remove(path.size() - 1);
}
if (root.right != null) {
dfs(root.right, cur + root.right.val);
path.remove(path.size() - 1);
}
}
Análisis de la complejidad
- Complejidad de tiempo: ,
- Espacio de la complejidad: ,
Segundo método: Optimizar
No necesitamos otra dentro de cada método, junto con la izquierda juicio, a la derecha, sustituida por una sentencia de la raíz más que no esté vacía en el proceso de comenzar.
List<List<Integer>> paths = null;
List<Integer> path = null;
public List<List<Integer>> pathSum(TreeNode root, int sum) {
paths = new LinkedList<>();
path = new ArrayList<>();
dfs(root, sum);
return paths;
}
private void dfs(TreeNode root, int re) {
if (root == null) {
return;
}
path.add(root.val);
if (root.left == null && root.right == null && re == root.val) {
paths.add(new ArrayList<>(path));
path.remove(path.size()-1);
return;
}
dfs(root.left, re - root.val);
dfs(root.right, re - root.val);
path.remove(path.size()-1);
}
Análisis de la complejidad
- Complejidad de tiempo: ,
- Espacio de la complejidad: ,