BiruLyu
5/29/2017 - 5:39 PM

257. Binary Tree Paths(StringBuilder).java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new ArrayList<String>();
        if(root != null) helper(root, "", res);
        return res;
    }
    
    public void helper(TreeNode node, String str, List<String> res){
        if(node.left == null && node.right == null) res.add(str + node.val);
        if(node.left != null) helper(node.left, str + node.val + "->", res);
        if(node.right != null) helper(node.right, str + node.val + "->", res);
    }
}
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new ArrayList<String>();
        if (root == null) return res;
        StringBuilder sb = new StringBuilder();
        sb.append(root.val);
        if(root.left == null && root.right == null){//[1] Output : ["1"]
            res.add(sb.toString());
        } else {
            backtracking(root.left, res, sb);
            backtracking(root.right, res, sb);
        }
        
        return res;
    }
    
    public void backtracking(TreeNode root, List<String> res, StringBuilder temp){
        if(root == null) return;
        
        temp.append("->").append(root.val);
        
        if(root.left == null && root.right == null) {
            res.add(temp.toString());
            int last = temp.lastIndexOf("->");
            temp.setLength(last);
            return;
        }
        
        backtracking(root.left, res,temp);
        backtracking(root.right, res, temp);
        int last = temp.lastIndexOf("->");
        temp.setLength(last);
    }
}