二刷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 binaryTreePaths(TreeNode root) {
        List res = new ArrayList<>();
        if (root == null){
            return res;
        }
        StringBuilder path = new StringBuilder();
        dfsHelper(root, res, path);
        return res;    
    }
    
    private void dfsHelper(TreeNode root, List 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 binaryTreePaths(TreeNode root) {
        List res = new ArrayList<>();
        String path = root.val + "";
        dfsHelper(root, res, path);
        return res;    
    }
    
    private void dfsHelper(TreeNode root, List 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);
        }
    }
}

你可能感兴趣的:(二刷257. Binary Tree Paths)