Java AC solution


  • 1
    Y
    public class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> list = new ArrayList<String>();
        if(root == null)  return list;
        StringBuilder str = new StringBuilder();
        binaryHelper(root,list,str);
        return list;
    }
    
    private void binaryHelper(TreeNode root, List<String> list, StringBuilder str){
        if(root == null) return;
        StringBuilder newStr = new StringBuilder(str);
        if(newStr.length() != 0)
            newStr.append("->");
        newStr.append(root.val);
        if(root.left == null && root.right == null)
        {
            list.add(newStr.toString());
            return;
        }
            binaryHelper(root.left,list,newStr);
            binaryHelper(root.right,list,newStr);
    }
    

    }


Log in to reply
 

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