栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【Leetcode】257. 二叉树的所有路径

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【Leetcode】257. 二叉树的所有路径

题目描述

题解

能用String解决的最好不要走StringBuilder。递归时注意空结点(null)回退和叶子结点判定回退。

执行用时:9 ms, 在所有 Java 提交中击败了30.66%的用户

内存消耗:39.1 MB, 在所有 Java 提交中击败了5.11%的用户

通过测试用例:208 / 208


class Solution {
    List res = new ArrayList<>();
    
    public List binaryTreePaths(TreeNode root) {
        if (root == null)
            return res;
        recur(root, "");
        return res;
    }
    
    public void recur(TreeNode root, String path) {
        if (root == null) {
            return;
        }
        if (root.left == null && root.right == null) {
            res.add(path + root.val);
            return;
        }
        recur(root.left, path + root.val + "->");        
        recur(root.right, path + root.val + "->");
        return;
    }
}

反面教材:

通过测试用例:206 / 208

如果StringBuilder的话会非常麻烦,还要把加进去的string主动删掉,而且最后如果root.val数字长度不可预测,你根本不知道要删多少位。所以如果是这样还不如用一个List来装path。

class Solution {
    List res = new ArrayList<>();
    
    public List binaryTreePaths(TreeNode root) {
        if (root == null)
            return res;
        recur(root, new StringBuilder());
        return res;
    }
    
    public void recur(TreeNode root, StringBuilder path) {
        if (root == null) {
            return;
        }
        if (root.left == null && root.right == null) {
            res.add(path.append(root.val).toString());
            path.delete(path.length() - 1, path.length());
            return;
        }
        recur(root.left, path.append(root.val + "->"));
        path.delete(path.length() - 3, path.length());
        recur(root.right, path.append(root.val + "->"));
        path.delete(path.length() - 3, path.length());
        return;
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/294323.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号