Árbol y camino

Descripción del problema
Ingrese el nodo raíz de un árbol binario y un número entero, e imprima todas las rutas donde la suma de los valores del nodo en el árbol binario es el número entero de entrada. La ruta se define como una ruta que comienza desde el nodo raíz del árbol y baja al nodo hoja. (Nota: en la lista de valores de retorno, la matriz con la mayor longitud de matriz está en la parte superior)

在这里插入代码片
  private ArrayList<ArrayList<Integer>> listAll = new ArrayList<ArrayList<Integer>>();
    private ArrayList<Integer> list = new ArrayList<Integer>();
    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
        if(root == null) return listAll;
        list.add(root.val);
        target -= root.val;
        if(target == 0 && root.left == null && root.right == null)
            listAll.add(new ArrayList<Integer>(list));
        FindPath(root.left, target);
        FindPath(root.right, target);
        list.remove(list.size()-1);
        return listAll;
    }
Publicado 167 artículos originales · Me gusta 16 · Visitas 30,000+

Supongo que te gusta

Origin blog.csdn.net/feiqipengcheng/article/details/105468407
Recomendado
Clasificación