Java solution


  • 0
    U
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public List<List<String>> printTree(TreeNode root) {
            int[] dim = getDim(root);
            List<List<String>> matrix = buildMatrix(dim[0], dim[1]);
            fillMatrix(root, matrix, 0, matrix.get(0).size()-1, 0);
            return matrix;
        }
            
        private static int[] getDim(TreeNode root) {
            if (root == null) {
                return new int[]{0,0};
            }
            int[] left = getDim(root.left);
            int[] right = getDim(root.right);
            return new int[]{Math.max(left[0], right[0]) * 2 + 1, 1 + Math.max(left[1], right[1])};
        }
        
        private static List<List<String>> buildMatrix(int width, int height) {
            List<List<String>> matrix = new ArrayList<>();
    
            for (int i = 0; i < height; i++) {
                String[] arr = new String[width];
                Arrays.fill(arr,"");
                matrix.add(Arrays.asList(arr));
            }
            return matrix;
        }
        
        private static void fillMatrix(TreeNode root, List<List<String>> matrix, int left, int right, int depth) {
            if (depth >= matrix.size() || root == null) {
                return;
            }
            int mid = left + (right - left) / 2;
            matrix.get(depth).set(mid, String.valueOf(root.val));
            fillMatrix(root.left, matrix, left, mid - 1, depth + 1);
            fillMatrix(root.right, matrix, mid + 1, right, depth + 1);
        }
    }
    

Log in to reply
 

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