为什么我的代码没有给出根到叶路径打印问题的完美答案? [关闭]

问题描述 投票:0回答:0
public static void printPath(ArrayList<Integer> path) {
    for (int i = 0; i < path.size(); i++) {
        System.out.print(path.get(i) + " ->");
    }

    System.out.println("Null");
}

public static void printRoot2Leaf(Node root, ArrayList<Integer> path) {
    if (root == null) {
        return;
    }
    path.add(root.data);
  
    if (root.left == null && root.right == null) {
        printPath(path);
    }
    printRoot2Leaf(root.left, path);
    printRoot2Leaf(root.right, path);
    path.remove(path.size()-1);
}

我正在尝试打印根到叶的路径,但它没有给出正确的答案。我找不到问题所在。

java binary-search-tree
© www.soinside.com 2019 - 2024. All rights reserved.