Java, DFS, Beats 97%


  • 0
    K
    public class Solution {
        public List<String> binaryTreePaths(TreeNode root) {
            List<String> paths = new ArrayList<String>();
            paths(root, paths, "");
            return paths;
        }
        public void paths(TreeNode root, List<String> paths, String path) {
            if(root == null) {
              return;
            }
            path += root.val + "->";    
            paths(root.left, paths, path);
            paths(root.right, paths, path);
            if(root.left == null && root.right == null) {
              paths.add(path.substring(0, path.length()-2));
            }
      }
    }
    

Log in to reply
 

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