Related Articles
Given a binary tree, print all root-to-leaf paths
• Difficulty Level : Easy
• Last Updated : 18 Mar, 2019

For the below example tree, all root-to-leaf paths are:
10 –> 8 –> 3
10 –> 8 –> 5
10 –> 2 –> 2 ## Recommended: Please solve it on “PRACTICE” first, before moving on to the solution.

Algorithm:
Use a path array path[] to store current root to leaf path. Traverse from root to all leaves in top-down fashion. While traversing, store data of all nodes in current path in array path[]. When we reach a leaf node, print the path array.

## C++

 `#include ``using` `namespace` `std;`` ` `/* A binary tree node has data, pointer to left child ``and a pointer to right child */``class` `node ``{ ``    ``public``:``    ``int` `data; ``    ``node* left; ``    ``node* right; ``}; `` ` `/* Prototypes for funtions needed in printPaths() */``void` `printPathsRecur(node* node, ``int` `path[], ``int` `pathLen); ``void` `printArray(``int` `ints[], ``int` `len); `` ` `/*Given a binary tree, print out all of its root-to-leaf ``paths, one per line. Uses a recursive helper to do the work.*/``void` `printPaths(node* node) ``{ ``    ``int` `path; ``    ``printPathsRecur(node, path, 0); ``} `` ` `/* Recursive helper function -- given a node, ``and an array containing the path from the root``node up to but not including this node, ``print out all the root-leaf paths.*/``void` `printPathsRecur(node* node, ``int` `path[], ``int` `pathLen) ``{ ``    ``if` `(node == NULL) ``        ``return``; ``     ` `    ``/* append this node to the path array */``    ``path[pathLen] = node->data; ``    ``pathLen++; ``     ` `    ``/* it's a leaf, so print the path that led to here */``    ``if` `(node->left == NULL && node->right == NULL) ``    ``{ ``        ``printArray(path, pathLen); ``    ``} ``    ``else``    ``{ ``        ``/* otherwise try both subtrees */``        ``printPathsRecur(node->left, path, pathLen); ``        ``printPathsRecur(node->right, path, pathLen); ``    ``} ``} `` ` ` ` `/* UTILITY FUNCTIONS */``/* Utility that prints out an array on a line. */``void` `printArray(``int` `ints[], ``int` `len) ``{ ``    ``int` `i; ``    ``for` `(i = 0; i < len; i++) ``    ``{ ``        ``cout << ints[i] << ``" "``; ``    ``} ``    ``cout<data = data; ``    ``Node->left = NULL; ``    ``Node->right = NULL; ``     ` `    ``return``(Node); ``} `` ` `/* Driver code*/``int` `main() ``{ ``     ` `    ``/* Constructed binary tree is ``                ``10 ``            ``/ \ ``            ``8 2 ``        ``/ \ / ``        ``3 5 2 ``    ``*/``    ``node *root = newnode(10); ``    ``root->left = newnode(8); ``    ``root->right = newnode(2); ``    ``root->left->left = newnode(3); ``    ``root->left->right = newnode(5); ``    ``root->right->left = newnode(2); ``     ` `    ``printPaths(root); ``    ``return` `0; ``} `` ` `// This code is contributed by rathbhupendra`

## C

 `#include``#include``  ` `/* A binary tree node has data, pointer to left child``   ``and a pointer to right child */``struct` `node``{``   ``int` `data;``   ``struct` `node* left;``   ``struct` `node* right;``};`` ` `/* Prototypes for funtions needed in printPaths() */` `void` `printPathsRecur(``struct` `node* node, ``int` `path[], ``int` `pathLen);``void` `printArray(``int` `ints[], ``int` `len);`` ` `/*Given a binary tree, print out all of its root-to-leaf`` ``paths, one per line. Uses a recursive helper to do the work.*/``void` `printPaths(``struct` `node* node) ``{``  ``int` `path;``  ``printPathsRecur(node, path, 0);``}`` ` `/* Recursive helper function -- given a node, and an array containing`` ``the path from the root node up to but not including this node,`` ``print out all the root-leaf paths.*/``void` `printPathsRecur(``struct` `node* node, ``int` `path[], ``int` `pathLen) ``{``  ``if` `(node==NULL) ``    ``return``;`` ` `  ``/* append this node to the path array */``  ``path[pathLen] = node->data;``  ``pathLen++;`` ` `  ``/* it's a leaf, so print the path that led to here  */``  ``if` `(node->left==NULL && node->right==NULL) ``  ``{``    ``printArray(path, pathLen);``  ``}``  ``else` `  ``{``    ``/* otherwise try both subtrees */``    ``printPathsRecur(node->left, path, pathLen);``    ``printPathsRecur(node->right, path, pathLen);``  ``}``}`` ` ` ` `/* UTILITY FUNCTIONS */``/* Utility that prints out an array on a line. */``void` `printArray(``int` `ints[], ``int` `len) ``{``  ``int` `i;``  ``for` `(i=0; idata = data;``  ``node->left = NULL;``  ``node->right = NULL;``  ` `  ``return``(node);``}``  ` `/* Driver program to test above functions*/``int` `main()``{ ``  ` `  ``/* Constructed binary tree is``            ``10``          ``/   \``        ``8      2``      ``/  \    /``    ``3     5  2``  ``*/``  ``struct` `node *root = newnode(10);``  ``root->left        = newnode(8);``  ``root->right       = newnode(2);``  ``root->left->left  = newnode(3);``  ``root->left->right = newnode(5);``  ``root->right->left = newnode(2);``  ` `  ``printPaths(root);``  ` `  ``getchar``();``  ``return` `0;``}`

## Java

 `// Java program to print all the node to leaf path``  ` `/* A binary tree node has data, pointer to left child``   ``and a pointer to right child */``class` `Node ``{``    ``int` `data;``    ``Node left, right;``  ` `    ``Node(``int` `item) ``    ``{``        ``data = item;``        ``left = right = ``null``;``    ``}``}``  ` `class` `BinaryTree ``{``    ``Node root;``      ` `    ``/*Given a binary tree, print out all of its root-to-leaf``      ``paths, one per line. Uses a recursive helper to do ``      ``the work.*/``    ``void` `printPaths(Node node) ``    ``{``        ``int` `path[] = ``new` `int``[``1000``];``        ``printPathsRecur(node, path, ``0``);``    ``}``  ` `    ``/* Recursive helper function -- given a node, and an array``       ``containing the path from the root node up to but not ``       ``including this node, print out all the root-leaf paths.*/``    ``void` `printPathsRecur(Node node, ``int` `path[], ``int` `pathLen) ``    ``{``        ``if` `(node == ``null``)``            ``return``;``  ` `        ``/* append this node to the path array */``        ``path[pathLen] = node.data;``        ``pathLen++;``  ` `        ``/* it's a leaf, so print the path that led to here  */``        ``if` `(node.left == ``null` `&& node.right == ``null``)``            ``printArray(path, pathLen);``        ``else` `        ``{``            ``/* otherwise try both subtrees */``            ``printPathsRecur(node.left, path, pathLen);``            ``printPathsRecur(node.right, path, pathLen);``        ``}``    ``}``  ` `    ``/* Utility function that prints out an array on a line. */``    ``void` `printArray(``int` `ints[], ``int` `len) ``    ``{``        ``int` `i;``        ``for` `(i = ``0``; i < len; i++) ``        ``{``            ``System.out.print(ints[i] + ``" "``);``        ``}``        ``System.out.println(``""``);``    ``}``  ` `    ``// driver program to test above functions``    ``public` `static` `void` `main(String args[]) ``    ``{``        ``BinaryTree tree = ``new` `BinaryTree();``        ``tree.root = ``new` `Node(``10``);``        ``tree.root.left = ``new` `Node(``8``);``        ``tree.root.right = ``new` `Node(``2``);``        ``tree.root.left.left = ``new` `Node(``3``);``        ``tree.root.left.right = ``new` `Node(``5``);``        ``tree.root.right.left = ``new` `Node(``2``);``         ` `        ``/* Let us test the built tree by printing Insorder traversal */``        ``tree.printPaths(tree.root);``    ``}``}`` ` `// This code has been contributed by Mayank Jaiswal`

## Python3

 `"""``Python program to print all path from root to``leaf in a binary tree``"""`` ` `# binary tree node contains data field , ``# left and right pointer``class` `Node:``    ``# constructor to create tree node``    ``def` `__init__(``self``, data):``        ``self``.data ``=` `data``        ``self``.left ``=` `None``        ``self``.right ``=` `None`` ` `# function to print all path from root``# to leaf in binary tree``def` `printPaths(root):``    ``# list to store path``    ``path ``=` `[]``    ``printPathsRec(root, path, ``0``)`` ` `# Helper function to print path from root ``# to leaf in binary tree``def` `printPathsRec(root, path, pathLen):``     ` `    ``# Base condition - if binary tree is``    ``# empty return``    ``if` `root ``is` `None``:``        ``return`` ` `    ``# add current root's data into ``    ``# path_ar list``     ` `    ``# if length of list is gre``    ``if``(``len``(path) > pathLen): ``        ``path[pathLen] ``=` `root.data``    ``else``:``        ``path.append(root.data)`` ` `    ``# increment pathLen by 1``    ``pathLen ``=` `pathLen ``+` `1`` ` `    ``if` `root.left ``is` `None` `and` `root.right ``is` `None``:``         ` `        ``# leaf node then print the list``        ``printArray(path, pathLen)``    ``else``:``        ``# try for left and right subtree``        ``printPathsRec(root.left, path, pathLen)``        ``printPathsRec(root.right, path, pathLen)`` ` `# Helper function to print list in which ``# root-to-leaf path is stored``def` `printArray(ints, ``len``):``    ``for` `i ``in` `ints[``0` `: ``len``]:``        ``print``(i,``" "``,end``=``"")``    ``print``()`` ` `# Driver program to test above function``"""``Constructed binary tree is ``            ``10``        ``/ \``        ``8     2``    ``/ \ /``    ``3 5 2``"""``root ``=` `Node(``10``)``root.left ``=` `Node(``8``)``root.right ``=` `Node(``2``)``root.left.left ``=` `Node(``3``)``root.left.right ``=` `Node(``5``)``root.right.left ``=` `Node(``2``)``printPaths(root)`` ` `# This code has been contributed by Shweta Singh.`

## C#

 `using` `System;`` ` `// C# program to print all the node to leaf path `` ` `/* A binary tree node has data, pointer to left child ``   ``and a pointer to right child */``public` `class` `Node``{``    ``public` `int` `data;``    ``public` `Node left, right;`` ` `    ``public` `Node(``int` `item)``    ``{``        ``data = item;``        ``left = right = ``null``;``    ``}``}`` ` `public` `class` `BinaryTree``{``    ``public` `Node root;`` ` `    ``/*Given a binary tree, print out all of its root-to-leaf ``      ``paths, one per line. Uses a recursive helper to do  ``      ``the work.*/``    ``public` `virtual` `void` `printPaths(Node node)``    ``{``        ``int``[] path = ``new` `int``;``        ``printPathsRecur(node, path, 0);``    ``}`` ` `    ``/* Recursive helper function -- given a node, and an array ``       ``containing the path from the root node up to but not  ``       ``including this node, print out all the root-leaf paths.*/``    ``public` `virtual` `void` `printPathsRecur(Node node, ``int``[] path, ``int` `pathLen)``    ``{``        ``if` `(node == ``null``)``        ``{``            ``return``;``        ``}`` ` `        ``/* append this node to the path array */``        ``path[pathLen] = node.data;``        ``pathLen++;`` ` `        ``/* it's a leaf, so print the path that led to here  */``        ``if` `(node.left == ``null` `&& node.right == ``null``)``        ``{``            ``printArray(path, pathLen);``        ``}``        ``else``        ``{``            ``/* otherwise try both subtrees */``            ``printPathsRecur(node.left, path, pathLen);``            ``printPathsRecur(node.right, path, pathLen);``        ``}``    ``}`` ` `    ``/* Utility function that prints out an array on a line. */``    ``public` `virtual` `void` `printArray(``int``[] ints, ``int` `len)``    ``{``        ``int` `i;``        ``for` `(i = 0; i < len; i++)``        ``{``            ``Console.Write(ints[i] + ``" "``);``        ``}``        ``Console.WriteLine(``""``);``    ``}`` ` `    ``// driver program to test above functions ``    ``public` `static` `void` `Main(``string``[] args)``    ``{``        ``BinaryTree tree = ``new` `BinaryTree();``        ``tree.root = ``new` `Node(10);``        ``tree.root.left = ``new` `Node(8);``        ``tree.root.right = ``new` `Node(2);``        ``tree.root.left.left = ``new` `Node(3);``        ``tree.root.left.right = ``new` `Node(5);``        ``tree.root.right.left = ``new` `Node(2);`` ` `        ``/* Let us test the built tree by printing Insorder traversal */``        ``tree.printPaths(tree.root);``    ``}``}`` ` `// This code is contributed by Shrikant13`

Output :
```10 8 3
10 8 5
10 2 2 ```

Time Complexity: O(n2) where n is number of nodes.

Please write comments if you find any bug in above codes/algorithms, or find other ways to solve the same problem.

My Personal Notes arrow_drop_up