前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >​LeetCode刷题实战257:二叉树的所有路径

​LeetCode刷题实战257:二叉树的所有路径

作者头像
程序员小猿
发布2021-05-28 10:48:57
2180
发布2021-05-28 10:48:57
举报
文章被收录于专栏:程序IT圈

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 二叉树的所有路径,我们先来看题面:

https://leetcode-cn.com/problems/binary-tree-paths/

Given the root of a binary tree, return all root-to-leaf paths in any order. A leaf is a node with no children.

给定一个二叉树,返回所有从根节点到叶子节点的路径。说明: 叶子节点是指没有子节点的节点。

解题

代码语言:javascript
复制
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 * int val;
 * TreeNode left;
 * TreeNode right;
 * TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public  List<String> binaryTreePaths(TreeNode root) {
        List<String> list = new LinkedList<>();
        helper(root, "", list);
        return list;
    }
    
    private void helper(TreeNode root, String s, List<String>list){
        if (root == null){
            return;
        }
        
        s = s + root.val;
        
        if (root.left == null && root.right == null){
            list.add(s);
            return;
        }
        
        if (root.left != null){
            helper(root.left, s + "->", list);
        }

        if (root.right != null){
            helper(root.right, s + "->", list);
        }
    }
 
    
 
}

好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-05-06,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 程序员小猿 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 解题
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档