My recursive O(n) solution


  • 0
    P
    public class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> paths = new LinkedList<String>();
        if(root != null)
        binaryTreePaths(root,paths, "");
        return paths;
    }
    public void binaryTreePaths(TreeNode root, List<String> paths, String path) {
        StringBuilder pathb = new StringBuilder(path);
        pathb.append(root.val);
        if(root.left == null && root.right == null) {
            paths.add(pathb.toString());
            return;
        } else {
            pathb.append("->");
            String curPath = pathb.toString();
            if(root.left != null) binaryTreePaths(root.left, paths, curPath);
            if(root.right != null) binaryTreePaths(root.right,paths, curPath);
        }
    }
    

    }


  • 0

    In your "O(n)", what is n?


  • 0
    M
    public class Solution {
    
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> list = new ArrayList<>();
        if (root == null)   return list;
        getPaths(root, list, new StringBuilder());
        return list;
    }
            
    private void getPaths(TreeNode root, List<String> list, StringBuilder sb) {
        if (root != null) {
            if (root.left == null && root.right == null) {
                list.add(sb.toString() + root.val);
            } else {
                if (root.left != null) {
                getPaths(root.left, list, sb.append(root.val).append("->"));
                sb.delete(sb.lastIndexOf(String.valueOf(root.val)), sb.length());                    
            }
            if (root.right != null) {
                getPaths(root.right, list, sb.append(root.val).append("->"));
                sb.delete(sb.lastIndexOf(String.valueOf(root.val)), sb.length());
            }
        }
    }
    }
    

  • 0
    M

    This is very similar to the above solution with a DFS style traversal with O(n) and n refers to number of nodes in the tree.


Log in to reply
 

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