257_Binary Tree Paths

257. Binary Tree Paths

Level: easy

Tag: tree, dfs

Question

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

Example 1

given the following binary tree:

   1
 /   \
2     3
 \
  5

All root-to-leaf paths are:

["1->2->5", "1->3"]

Solution 1: recursive

递归实现深度优先遍历。注意要记录途中访问过的节点,遇到叶子节点时可以生成一条路径字符串。关于记录路径,先保存在数组里,需要生成路径时再生成。

Another version (w/o defining a helper function)

Solution 2: iterative (Depth first search, using stack)

Solution 3: iterative (Breadth first search, using stack) ??

Last updated

Was this helpful?