FastPrepAll Root-to-Leaf Paths in a Binary Tree

All Root-to-Leaf Paths in a Binary Tree

Google logoGoogle● EasyINTERNONSITE INTERVIEW
Learn

Problem statement

Given the root of a binary tree, return every path from the root to a leaf.

  • Serialize a path by joining its node values with ->.
  • Return paths in left-to-right depth-first order: completely visit a node's left subtree before its right subtree.
  • Return an empty array for an empty tree.

A leaf has no left child and no right child. Do not use global or static mutable state.

Deep-tree follow-up

How can an explicit stack preserve the same traversal and backtracking behavior without risking recursive call-stack overflow?

Function

binaryTreePaths(root: TreeNode) → String[]

Examples

Example 1

root = [1,2,3,null,5]return = ["1->2->5","1->3"]

The left leaf produces 1->2->5, followed by the right leaf path 1->3.

Example 2

root = [1]return = ["1"]

The root is also a leaf, so the only path contains its value.

Example 3

root = []return = []

An empty tree has no root-to-leaf paths.

Example 4

root = [-1,-2,3,null,-4]return = ["-1->-2->-4","-1->3"]

Negative values are preserved in the path strings, and the left path still appears before the right path.

Constraints

  • The tree contains between 0 and 100000 nodes.
  • -2^31 <= Node.val <= 2^31 - 1.
  • The tree may be skewed to a depth of 100000.

More Google problems

See Google hiring insights
public String[] binaryTreePaths(TreeNode root) {
  // Write your code here.
}
root[1,2,3,null,5]
expected["1->2->5", "1->3"]
Checking account…