257--Binary-Tree-Paths-1
文章目录
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
|
|
All root-to-leaf paths are:
[“1->2->5”, “1->3”]
解题分析
The time complexity for the problem should be O(n), since we are basically visiting each node in the tree. Yet an interviewer might ask you for further optimization when he or she saw a string concatenation. A string concatenation is just too costly. A StringBuilder can be used although a bit tricky since it is not immutable like string is.
When using StringBuilder, We can just keep track of the length of the StringBuilder before we append anything to it before recursion and afterwards set the length back. Another trick is when to append the “->”, since we don’t need the last arrow at the end of the string, we only append it before recurse to the next level of the tree. Hope the solution helps!
|
|
文章作者 Hustbill
上次更新 2017-04-26