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

Solution:DFS

Time Complexity: O(N) Space Complexity: O(N) 递归缓存

Solution Code:

class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> result = new ArrayList<>();
        dfs(root, "", result);
        return result;
    }
    
    private void dfs(TreeNode node, String cur_res, List<String> result) {
        if(node == null) return;
        if(node.left == null && node.right == null) {
            result.add(cur_res + String.valueOf(node.val));
            return;
        }
        cur_res += String.valueOf(node.val) + "->";
        dfs(node.left, cur_res, result);
        dfs(node.right, cur_res, result);
    } 
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,364评论 0 33
  • Given a binary tree, return all root-to-leaf paths. For e...
    番茄晓蛋阅读 1,553评论 0 0
  • 存储过程的优缺点: 优点: 1.由于应用程序随着时间推移会不断更改,增删功能,T-SQL过程代码会变得更复杂,St...
    目标肢解阅读 11,351评论 0 2
  • 幸福是快快乐乐的生活。活在真实里,不虚假,不做作。有自己的想法。 以前想穿上好看的衣服,想吃好吃的东西。后来明白,...
    小秀子乖乖阅读 1,148评论 0 0
  • 人的忍受功能堪称浅力无边。 当你随着人流不断前行,你得忍受不知从哪串出来的急火火、比赶飞机还急的冒失鬼,毫...
    Fwx烟雨倾城阅读 1,751评论 0 1

友情链接更多精彩内容