Я работаю над проблемой для печати всех путей двоичного дерева, и это дает результат. Создать глобальный переменную ЕО, а также в рекурсии printAllRootToLeafPaths метод, строковая переменная путь используются. Есть ли какой-нибудь способ, которым я могу сделать Sw и путь только внутри printAllRootToLeafPaths метод? Таким образом, метод будет выглядеть следующим образом.Печать всех путей двоичного дерева
public static ArrayList<String> printAllRootToLeafPaths(TreeNode node){
/*
String path and ArrayList<String> sw will be initiated here
*/
}
==============================================================================
import java.io.*;
import java.util.*;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public class myTest {
public static ArrayList<String> sw = new ArrayList<String>();
public static void main (String[] args){
TreeNode root = new TreeNode(1);
root.left= new TreeNode(2) ;
root.left.left = new TreeNode(5);
root.right = new TreeNode(3);
sw = printAllRootToLeafPaths(root, new String());
String[] result = new String[ sw.size() ];
int count = 0 ;
for (String s: sw){
result[count] = '"'+ s + '"';
count++;
}
System.out.println(Arrays.toString(result));
}
public static ArrayList<String> printAllRootToLeafPaths(TreeNode node, String path) {
if(node==null) return null ;
path += String.valueOf(node.val)+ "->";
if(node.left == null && node.right == null){
String my = path.substring(0, path.length() -2);
sw.add(my);
// optional
path = "";
}
else {
printAllRootToLeafPaths(node.left, new String (path));
printAllRootToLeafPaths(node.right, new String (path) );
}
return sw ;
}
}
Может быть, я не» Правильно поймите ответ. Я хотел бы использовать метод printAllRootToLeafPaths только с одним аргументом -> printAllRootToLeafPaths (узел TreeNode). Кроме того, где мне нужно инициировать sw и path? –