Java Recursive Solution with pre-initialization


  • 0
    P
    public class Solution {
        public List<List<String>> printTree(TreeNode root) {
            int depth = getDepth(root, 0);
            int width = (int)Math.pow(2, depth + 1) - 1;
            
            List<List<String>> output = getPrintedTree(depth, width);
            print(root, 0, 0, width - 1, output);
            return output;       
        }
        
        private void print(TreeNode node, int level, int s, int e, List<List<String>> output) {
            int pos = (e + s) / 2;
            output.get(level).set(pos, String.valueOf(node.val));
            if(node.left != null) print(node.left, level + 1,  s, pos - 1, output);
            if(node.right != null) print(node.right, level + 1, pos + 1, e, output);
        }
        
        private List<List<String>> getPrintedTree(int depth, int width) {
            List<List<String>> response = new ArrayList<>(depth + 1);    
            for(int i = 0; i <= depth; i++) {
                response.add(getRow(width));
            }
            return response;
        }
        
        private List<String> getRow(int width) {
            String[] array = new String[width];
            Arrays.fill(array, "");
            return Arrays.asList(array);
        }
        
        private int getDepth(TreeNode node, int level) {
            int leftMax = node.left != null ? getDepth(node.left, level + 1) : level;
            int rightMax = node.right != null ? getDepth(node.right, level + 1) : level;
            return Math.max(leftMax, rightMax);
        }
    }
    

Log in to reply
 

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