257. Binary Tree Paths

Given a binary tree, return all root-to-leaf paths.

Note: A leaf is a node with no children.

Example:

Input:

1
/ \
2 3
\
5

Output: ["1->2->5", "1->3"]

Explanation: All root-to-leaf paths are: 1->2->5, 1->3
Accepted
240,281
Submissions
512,802

Solution

刚开始为了必变出现string + string这种操作使用LinkedList保存中间值,但是发现耗时反而比较长

Complexity

O(N) O(N);

Code

/**
 * 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;
        helper(root, "", res);
        return res;
    }
    public void helper(TreeNode root, String s, List<String> res){
        if(root == null) return;
        if(root.left == null && root.right == null){
            res.add(s + root.val);
            return;
        }
        helper(root.left, s + root.val + "->", res);
        helper(root.right, s + root.val + "->", res);
    }
}