思想:找规律结合二分思想,结果集的长度应该为该树的层数m,而每层的长度(宽度)=树的深度=2^m - 1
然后每次把根节点插入到该层的中间位置mid=(start+end)/2上,然后左子树对应的插入区间为[start,mid-1],右子树的插入区间为[mid+1,end]然后同样也是将左右子树的根节点插入到它们区间的mid位置上,其他位置默认为空串
时间复杂度O(h * 2^h),h为树的高度,Arrays.fill() 它的时间复杂度为O(2^h)
空间复杂度O(h * 2^h) , 每层有2^h-1个数
class Solution {
private int getDepth(TreeNode root){
if(root==null)return 0;
if(root.left==null&&root.right==null)return 1;
int leftDepth = getDepth(root.left);
int rightDepth = getDepth(root.right);
return Math.max(leftDepth,rightDepth)+1;
}
private void helper(String[][]res,int idx,int start,int end,TreeNode root){
if(root==null){
return;
}
int mid = (start+end)/2;
res[idx][mid] = String.valueOf(root.val);
helper(res,idx+1,start,mid-1,root.left);
helper(res,idx+1,mid+1,end,root.right);
}
public List<List<String>> printTree(TreeNode root) {
List<List<String>> res = new ArrayList<>();
if(root==null)return res;
//行数m=树的深度(层数)
int m = getDepth(root);
//列数n
int n = ((int)Math.pow(2,m))-1;
String[][] str = new String[m][n];
for(int i=0;i<m;i++){
Arrays.fill(str[i],"");
}
helper(str,0,0,n-1,root);
for(String[] s:str){
res.add(Arrays.asList(s));
}
return res;
}
}