/**
 * 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> result = new ArrayList<>();
        generatePaths(root, result, new ArrayList<>());
        
        return result;
    }
    
    private void generatePaths(TreeNode root, List<String> result, List<String> currentPath) {
        if (root == null) {
            return;
        }
        currentPath.add(String.valueOf(root.val));
        if (root.left == null && root.right == null) {
            result.add(String.join("->", currentPath));
            currentPath.remove(currentPath.size() - 1);
            return;
        }
        
        generatePaths(root.left, result, currentPath);
        generatePaths(root.right, result, currentPath);
        currentPath.remove(currentPath.size() - 1);
    }
}

 

 

1. If use StringBuilder as path recorder, do not just remove ONE since it could be multi-digits number.

2. Remember to construct string with "->" if it is required.

 

Second approach:

1. Add path check both children.

2. "->" is added after value. So do not skip first element.

posted on 2017-08-20 11:15  keepshuatishuati  阅读(99)  评论(0编辑  收藏  举报