Print root to node path in BT

Binary Trees FAQs Hard

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.

Examples:

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.

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

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

Explanation :

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

Constraints

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

Hints

  • Start from the root node and traverse the tree recursively. Maintain a current path list that stores nodes visited so far.
  • When reaching a leaf node, store the current path in the result list. Use backtracking to remove the last node when returning from recursion.

Company Tags

Cloudflare Lyft Docker Etsy Shopify Boston Consulting Group Johnson & Johnson Bain & Company Rakuten Teladoc Health Flipkart Byju's Chewy Oracle Square Rockstar Games Micron Technology ARM Walmart Activision Blizzard Ernst & Young Ubisoft Salesforce Cerner OYO Rooms Google Microsoft Amazon Meta Apple Netflix Adobe