二刷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);
        }
    }
}
    原文作者:greatfulltime
    原文地址: https://www.jianshu.com/p/b2c316cd65dc
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞