Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Print All Root To Leaf Paths

Hard Acceptance 68.59% Points 40.00

You are given the root of a binary tree. Your task is to return all root-to-leaf paths. Each path should contain the node values from the root to a leaf.

A root-to-leaf path is a path that:

  • Starts from the root node.
  • Ends at a leaf node (a node with no children).
  • Contains all node values encountered along the path.

Return a list containing all such paths.

Examples
Example 1

image Input: root = [1,2,3,null,5]
Output: [[1,2,5],[1,3]]
Explanation: The tree has two root-to-leaf paths.

Example 2

image Input: root = [1]
Output: [[1]]
Explanation: The root itself forms the only root-to-leaf path.

Example 3

image Input: root = []
Output: []
Explanation: The tree contains no root-to-leaf paths.

Constraints
    • 0 = Number of nodes = 105
    • -10? = Node.data = 10?
Companies
Microsoft Bloomberg J.P. Morgan
Topics
Tree Traversal Binary Tree
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions