-1
   static void printAllPathsFromRootToLeaf (BinaryTree<Integer> tree, ArrayList<Integer> path)
{
    if (tree.isEmpty())
    {
        System.out.println("Tree is Empty");
        return;
    }
    path.add(tree.root());

    if (tree.left().isEmpty() && tree.right().isEmpty())
    {
        System.out.println(path);
        printSum(path);
        //return;
    }
    else
    {
        printAllPathsFromRootToLeaf(tree.left(),new ArrayList(path));
        printAllPathsFromRootToLeaf(tree.right(),new ArrayList(path));
    }
}

打印路径时,它只打印最后一条路径,或者只打印我的树中的一条路径。有人知道为什么吗??

谢谢你!

4

1 回答 1

0

它只打印最后一条路径,或者它只打印我树中的一条路径

这是因为您已选择使用此行来执行此操作:

if (tree.left().isEmpty() && tree.right().isEmpty())

AKA 如果节点是叶节点,则打印它。

将此添加到 else 语句

else
{
    System.out.println(path); //Not exactly sure what printing an ArrayList like this does, but you say it is doing what you want.
    printSum(path);
    printAllPathsFromRootToLeaf(tree.left(),new ArrayList(path));
    printAllPathsFromRootToLeaf(tree.right(),new ArrayList(path));
}
于 2013-04-01T22:19:12.253 回答