What's wrong in my solution ?


  • 0
    T
    public class Solution {
    static List<String> allPathStr = new ArrayList<String>();
    
    public List<String> binaryTreePaths(TreeNode root) {
        
        if(root == null){
            return new ArrayList<String>();
        }
        String path = "";
        binaryTreeAllPaths(root, path);
        
        return allPathStr;
    }
    
    public static void binaryTreeAllPaths(TreeNode root, String path){
        if(root != null){
            if(path == null || path.length() == 0){
                path = path + root.val;
            }        
            else {
                path = path + "->"+ root.val;
            }
    
            if((root.left == null) && (root.right == null)){
                allPathStr.add(path);
            }
            else {
                binaryTreeAllPaths(root.left, path);
                binaryTreeAllPaths(root.right, path);
            }
        }
    }
    }
    

    Hi guys,
    My code is failing for this test case:
    Input : [1,2]
    Output : ["1","1->2"]
    Expected : ["1->2"]

    It works perfectly fine on Eclipse. Any idea where is it wrong ?


  • 1

    Please avoid using static variables. Please read the FAQ for more information.


  • 0
    T

    Thanks a lot.
    I removed the static variable and passed it as method argument.
    It worked like a charm. :)


Log in to reply
 

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