# Binary Tree Paths – Given a binary tree, return all root-to-leaf paths.

### Problem.

Given a binary tree, return all root-to-leaf paths.

• 1->2->3
• 1->2->5
• 1->3

### Solution

#### TreeNode Data Structure

```package com.programtalk.learn.interview.questions;
class TreeNode {
TreeNode left, right;
int val;

TreeNode(int val) {
this.val = val;
left = right = null;
}
}

```

#### Binary Tree Solution

```package com.programtalk.learn.interview.questions;

import java.util.ArrayList;
import java.util.List;

public class BinaryTreePath2Root {

public List<List<Integer>> binaryTreePaths(TreeNode root) {
if (root != null){
}
}

private void searchBT(TreeNode root, List<Integer> currentPath, List<List<Integer>> allPaths) {
if (root.left == null && root.right == null){
return;
}

if (root.left != null){
searchBT(root.left,  new ArrayList<>(currentPath), allPaths);
}

if (root.right != null){
searchBT(root.right,  new ArrayList<>(currentPath), allPaths);
}
}

public static void main(String args[]) {
BinaryTreePath2Root tree = new BinaryTreePath2Root();
TreeNode  root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);

System.out.println(tree.binaryTreePaths(root));
}
}

```

#### OutPut

```[[1, 2, 4], [1, 2, 5], [1, 3]]
```

This site uses Akismet to reduce spam. Learn how your comment data is processed.