Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1
/ \
2 3
\
5
All root-to-leaf paths are:
[“1->2->5”, “1->3”]
解法1: DFS, O(N)
很标准的DFS的题目,要注意的是因为我们需要加入“->”, 所以写法上可以有两种办法。
一个是helper函数的起始string是“”, 那么每次加一个node的时候要判断是否str还是空,是的话不加,不是则加箭头。
另一个是一开始就赋值root->val, 这样每次碰到新node的时候一定需要加上”->”。写法上第二种办法更干净一些。
C++
Java