257. Binary Tree Paths

problem description

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

Note: A leaf is a node with no children.

Example:

Input:

   1
 /   \
2     3
 \
  5

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

Explanation: All root-to-leaf paths are: 1->2->5, 1->3

algorithm thought

就是将DFS的路线标记出来,最后返回。直接使用DFS做即可

只是这题需要注意一些细节,不然容易过不了一些测试样例

code

algorithm analysis

DFS将树遍历一遍,时间复杂度O(n)。

Last updated