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

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

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

解题

/**
 * 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);
        }
    }
 
    
 
}

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

上期推文:

LeetCode1-240题汇总,希望对你有点帮助!

LeetCode刷题实战241:为运算表达式设计优先级

LeetCode刷题实战242:有效的字母异位词

LeetCode刷题实战243:最短单词距离

LeetCode刷题实战244:最短单词距离 II

LeetCode刷题实战245:最短单词距离 III

LeetCode刷题实战246:中心对称数

LeetCode刷题实战247:中心对称数II

LeetCode刷题实战248:中心对称数III

LeetCode刷题实战249:移位字符串分组

LeetCode刷题实战250:统计同值子树

LeetCode刷题实战251:展开二维向量

LeetCode刷题实战252:会议室

LeetCode刷题实战253:会议室II

LeetCode刷题实战254:因子的组合

LeetCode刷题实战255:验证前序遍历序列二叉搜索树

LeetCode刷题实战256:粉刷房子

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员小猿666

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值