257. 二叉树的所有路径

257. 二叉树的所有路径_第1张图片

class Solution {
    public List binaryTreePaths(TreeNode root) {
        List paths = new ArrayList<>();
        constructPath(root,"",paths);
        return paths;
    }

    private void constructPath(TreeNode root, String path, List paths) {
        if(root == null){
            return;
        }
        StringBuffer pathSB = new StringBuffer(path);
        pathSB.append(Integer.toString(root.val));
        if(root.left == null && root.right == null){
            paths.add(pathSB.toString());
        }else {
            pathSB.append("->");
            constructPath(root.left,pathSB.toString(),paths);
            constructPath(root.right,pathSB.toString(),paths);
        }
    }
}

 

你可能感兴趣的:(leetcode,java,leetcode,开发语言)