Given a binary tree
5 / \ 2 3 / \ 4 10
All paths are {5,2,4}, {5,2,10}, {5,3}
public void printBinaryTreePath(TreeNode node) {
if (node==null) {
return;
}
printBinaryTreePath(node, new ArrayList<TreeNode>());
}
public void printBinaryTreePath(TreeNode node, List<TreeNode> paths) {
paths.add(node);
if (node.left==null&&node.right==null) {
for (TreeNode path : paths) {
System.out.print(path.val+" ");
}
System.out.println();
} else {
if (node.left!=null) {
printBinaryTreePath(node.left, paths);
}
if (node.right!=null){
printBinaryTreePath(node.right, paths);
}
}
paths.remove(paths.size()-1);
}