195. Print root to leaf path in BT

Given the root of a binary tree. Return all the root-to-leaf paths in the binary tree.

A leaf node of a binary tree is the node which does not have a left and right child.

Example 1:

Input : root = [1, 2, 3, null, 5, null, 4]

Output : [ [1, 2, 5] , [1, 3, 4] ]

Explanation : There are only two paths from root to leaf.

From root 1 to 5 , 1 -> 2 -> 5.

From root 1 to 4 , 1 -> 3 -> 4.

Example 2:

Input : root = [1, 2, 3, 4, 5]

Output : [ [1, 2, 4] , [1, 2, 5] , [1, 3] ]

Explanation :

Now Your Turn!

Pick the correct output for the given input

Input : root = [1, 2, 3, 4, null, 5, 6, null, 7]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= Number of Nodes <= 3*103
  • -103 <= Node.val <= 103

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
/**
* Definition for a binary tree node.
* struct TreeNode {
* int data;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int val) : data(val) , left(nullptr) , right(nullptr) {}
* };
**/
 
class Solution{
public:
vector<vector<int>> allRootToLeaf(TreeNode* root) {
//your code goes here
}
};
Test Case

Input:

Root