我正在處理打印二叉樹的所有路徑的問題,並給出結果。我創建一個全局變量SW以及在printAllRootToLeafPaths正在使用方法,String變量路徑的遞歸。有一些辦法可以讓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(TreeNode節點)來使用printAllRootToLeafPaths方法。此外,我需要在哪裏啓動sw和路徑? –