2ms Java solution with recursion, beats 70%, O(n) time and O(logN * logN) space


  • 0
    R
        public List<String> binaryTreePaths(TreeNode root) {
    		List<String> res = new LinkedList<>();
    		if (root == null)
    			return res;
    		String route = Integer.toString(root.val);
    		if (root.left == null && root.right == null) {
    		    res.add(route);
    		    return res;
    		}
    		binaryTreePaths(root.left, route, res);
    		binaryTreePaths(root.right, route, res);
    		return res;
    	}
    	
    	private void binaryTreePaths(TreeNode node, String route, List<String> res) {
    		if (node != null) {
    			route = route + "->" + node.val;
    			if (node.left == null && node.right == null) {
    				res.add(route);
    				return;
    			}
    			binaryTreePaths(node.left, route, res);
    			binaryTreePaths(node.right, route, res);
    		}
    	}
    

    I am not familiar with how to calculate the time complexity and space complexity. If they are wrong, please kindly let me know. Thank you very much.


Log in to reply
 

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