1
我想了解基本上打印二叉樹路徑的下列遞歸代碼的功能。遞歸期間的字符串參數
//Node has int val; Node left; Node right;
public List<String> printPaths(Node root) {
List<String> paths = new ArrayList<String>();
printPaths(root, paths, Integer.toString(root.val)); //root is not null
return paths;
}
public void printPaths(Node root, List<String> paths, String onePath) {
if(root.left == null && root.right == null) {
paths.add(onePath);
}
if (root.left != null) {
printPaths(root.left, paths, onePath + Integer.toString(root.left.val));
}
if (root.right != null) {
printPaths(root.left, paths, onePath + Integer.toString(root.right.val));
}
}
現在這種指紋的正確路徑值,但我不明白,因爲我更新onePath &不要重置它的價值如何被複位爲root.val每個單獨的路徑? 即使在爲前一個路徑追加「 - >」+ val之後,onePath值如何重置爲每個樹路徑的二叉樹根值?