Search⌘ K
AI Features

Challenge: Print All the Paths

Explore how to print every path from the root to the leaves in a binary tree using Go. This lesson guides you through traversing tree structures and outputting paths clearly, enhancing your understanding of recursion and tree traversal techniques.

Problem

Given a binary tree, print all the paths from the root to the leaves.

Input

The root of a binary tree.

Output

Display all paths in the binary tree.

Sample input

The root node t.root of a binary tree will be the input of printAllPath() function. We have to print all the paths of the given tree.

Here’s the sample input tree t.

t := LevelOrderBinaryTree(arr)

Sample output

All paths printed to the console using a semicolon (;) separated approach instead of line breaks.

7 3 1 ; 6 3 1 ; 10 5 2 1 ; 9 4 2 1 ; 8 4 2 1 

Note: Please add space after a semicolon too in order to successfully complete the exercise.

Let’s look at the illustration below to better understand the problem.

%0 node_1 1 node_2 2 node_1->node_2 node_3 3 node_1->node_3 node_1635146663140 4 node_2->node_1635146663140 node_1635146607111 5 node_2->node_1635146607111 node_1635146690643 8 node_1635146663140->node_1635146690643 node_1635146640676 9 node_1635146663140->node_1635146640676 node_1635146688645 10 node_1635146607111->node_1635146688645 node_1635146609445 6 node_3->node_1635146609445 node_1635146636321 7 node_3->node_1635146636321
PrintAllPath() = 7 3 1 ; 6 3 1 ; 10 5 2 1 ; 9 4 2 1 ; 8 4 2 1

Coding exercise

Try to solve this yourself first. If you get stuck or need help, you can always press the “Show Solution” button to see how your problem can be solved. We’ll look at the solution in the next lesson.

Good luck!

Go (1.6.2)
func (t *Tree) PrintAllPath() {
stk := new(Stack)
printAllPath(t.root, stk)
}
func printAllPath(curr *Node, stk *Stack) {
//Implement your solution here
//Kindly change this line of code as per your needs
fmt.Print("Sample Output")
//Implement your solution here
}