Given a binary tree, return all root-to-leaf paths.
Given the following binary tree:
All root-to-leaf paths are:
The following code is a recursive solution to find all paths of a binary tree from the root node to all leaf nodes. The core of the solution and the recursive method is named getPath(). For each node in the tree, we call this method once. For each recursive call, we keep track of the current path in a List named path. We also keep track of all the paths we found in a List named res.
getPath() first adds the current node to the path. Then it recursively calls getPath() once for the left child and once for the right child. When a leaf node is reached, utility method addResult() is called to add the string representation of the path to the list res. Before a recursive returns (backtracking), the last entry of path is removed.