Java,


  • 0

    Calculate height and width first. Build recursively.

    class Solution {
        public List<List<String>> printTree(TreeNode root) {
          List<String[]> rows = new ArrayList();
          int h = height(root);  
          int w = (int)Math.pow(2, h) - 1;
          helper(root, rows, 0, w, 0, w - 1);
          List<List<String>> res = new ArrayList();
          for(String[] r: rows){
            res.add(Arrays.asList(r));
          }
          return res;
        }
        
        private void helper(TreeNode root, List<String[]> rows, int h, int w, int s, int e){
          if(root == null) return;
          if(h == rows.size()){
            String[] newRow =  new String[w];
            Arrays.fill(newRow, "");
            rows.add(newRow);
            
          }
          String[] row = rows.get(h);
          int m = (s + e) / 2;
          row[m] = String.valueOf(root.val);
          helper(root.left, rows, h + 1, w, s, m - 1);
          helper(root.right, rows, h + 1, w, m + 1, e);
        }
        private int height(TreeNode root){
          if(root == null) return 0;
          return Math.max(height(root.left), height(root.right)) + 1;
        }
    }
    

Log in to reply
 

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