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));
}
}
打印路径时,它只打印最后一条路径,或者只在树中打印一条路径。谁会知道为什么?
谢谢!
答案 0 :(得分: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));
}