当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Printing Paths for Trees

问题描述:

 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));

}

}

When print the path it only prints the last path or it only prints one path in my tree. Would anyone know why??

THANK YOU!

网友答案:

it only prints the last path or it only prints one path in my tree

This is because you have choosen it to do so with this line:

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

AKA if the Node is a leaf Node, print it.

Add this to the else statement

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));
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: