257. Binary Tree Paths

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"]

解題分析

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!

// https://discuss.leetcode.com/topic/21474/accepted-java-simple-solution-in-8-lines/13
 public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        helper(res, root, sb);
        return res;
    }
    
    private void helper(List<String> res, TreeNode root, StringBuilder sb) {
        if(root == null) {
            return;
        }
        int len = sb.length();
        sb.append(root.val);
        if(root.left == null && root.right == null) {
            res.add(sb.toString());
        } else {
            sb.append("->");
            helper(res, root.left, sb);
            helper(res, root.right, sb);
        }
        sb.setLength(len);
    }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 9,900評論 0 23
  • 或許z有他的辦法,給自己解套。老吳可能想要一個兢兢業業的奮斗伙伴,因為他自己就是這樣的。他無法理解像z這樣...
    471503Liwufeng閱讀 115評論 0 0
  • 一段時間以來,我的靈魂跑的飛快,把身體搞得丟三拉四。 現在我站在了跑步機上開始跑步, 身體慢慢的動起來,這需要一點...
    牛頭馬蟻閱讀 235評論 0 0
  • 6次keep記錄 2次超級猩猩打卡 3月31日緯度 胸腰臀87-73-88,臍下81.3,體重99斤 1月31日緯...
    莎莎子20閱讀 254評論 0 0