2ms Java simple and fast solution using helper method--beats 75%


  • 1
    G

    using a variable pre to record the generated path before current root.

    public class Solution {
        List<String> paths = new LinkedList<>();
        public List<String> binaryTreePaths(TreeNode root) {
            if (root == null) return paths;
            findPaths(root, null);
            return paths;
        }
        
        private void findPaths(TreeNode root, String pre) {
            pre =(pre == null)? root.val + "": pre + "->" + root.val;
            if (root.left == null && root.right == null) {
                paths.add(pre);
                return;
            }
            if (root.left != null) findPaths(root.left, pre);
            if (root.right != null) findPaths(root.right, pre);
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.