Share my clean Java solution


  • 0
    K

    public class Solution {

    public List<String> binaryTreePaths(TreeNode root) {
        ArrayList<String> ans = new ArrayList();
        if(root == null)
            return ans;
        trav(root, "",ans);
        return ans;
    }
    
    public void trav(TreeNode cur, String path, ArrayList<String> ans)
    {
        path = path + cur.val;
        
        if(cur.left == null && cur.right == null) // leaf node
        {
            ans.add(path);
            return;
        }
     
        path = path + "->";
        if(cur.left != null)
            trav(cur.left, path, ans);
        if(cur.right != null)
            trav(cur.right, path, ans);
    }
    

    }


Log in to reply
 

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