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,967评论 0 23
  • 或许z有他的办法,给自己解套。老吴可能想要一个兢兢业业的奋斗伙伴,因为他自己就是这样的。他无法理解像z这样...
    471503Liwufeng阅读 116评论 0 0
  • 一段时间以来,我的灵魂跑的飞快,把身体搞得丢三拉四。 现在我站在了跑步机上开始跑步, 身体慢慢的动起来,这需要一点...
    牛头马蚁阅读 235评论 0 0
  • 6次keep记录 2次超级猩猩打卡 3月31日纬度 胸腰臀87-73-88,脐下81.3,体重99斤 1月31日纬...
    莎莎子20阅读 256评论 0 0