二刷257. Binary Tree Paths

Easy题
但是一开始不知为什么选择了StringBuilder没选String, 而且总觉得要backtracking.
要记得初始化一个string可以用String path = root.val + "", 就是whatever + ""就可以初始化一个string.
额,看了一圈答案,发现我最开始用StringBuilder + backtracking的思路是对的,update一下吧

/**
 * 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> res = new ArrayList<>();
        if (root == null){
            return res;
        }
        StringBuilder path = new StringBuilder();
        dfsHelper(root, res, path);
        return res;    
    }
    
    private void dfsHelper(TreeNode root, List<String> res, StringBuilder curtPath){
        if (root == null){
            return;
        }    
        if (root.left == null && root.right == null){
            curtPath.append(root.val);
            res.add(curtPath.toString());
            return;
        }
        curtPath.append(root.val);
        curtPath.append("->");
        int origLen = curtPath.length();
        dfsHelper(root.left, res, curtPath);
        curtPath.setLength(origLen);
        dfsHelper(root.right, res, curtPath);
        curtPath.setLength(origLen);
    }
}
/**
 * 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> res = new ArrayList<>();
        String path = root.val + "";
        dfsHelper(root, res, path);
        return res;    
    }
    
    private void dfsHelper(TreeNode root, List<String> res, String curtPath){
        if (root == null){
            return;
        }    
        if (root.left == null && root.right == null){
            res.add(curtPath);
            return;
        }
        if (root.left != null){
            dfsHelper(root.left, res, curtPath + "->" + root.left.val);
        }
        if (root.right != null){
            dfsHelper(root.right, res, curtPath + "->" + root.right.val);
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,769评论 0 33
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,904评论 18 139
  • Java 语言支持的类型分为两类:基本类型和引用类型。整型(byte 1, short 2, int 4, lon...
    xiaogmail阅读 1,365评论 0 10
  • Spark SQL, DataFrames and Datasets Guide Overview SQL Dat...
    Joyyx阅读 8,345评论 0 16
  • 昨晚睡觉做了个梦,很糊涂又很贴切。看了明星小s生日,说是婆家人为她庆生,有她的姐妹,母亲,而好友亲戚,唯独没有她的...
    番茄红阅读 351评论 0 0