LeetCode-655. Print Binary Tree(按照字符矩阵的形式打印二叉树)(二分和递归)
题目链接
题目
解析
找出对应的下标,然后二分递归遍历填充,先求出高度h,然后求出宽度为w = 2h-1,然后填充一个h行w列的字符矩阵即可,上下递归和左右二分夹杂在一起的感觉。具体看下图:
public List<List<String>> printTree(TreeNode root) {
List<List<String>> res = new ArrayList<>();
int h = height(root);
int w = (1 << h) - 1;
List<String> temp = new ArrayList<>();
for (int i = 0; i < w; i++) temp.add("");
for (int i = 0; i < h; i++) res.add(new ArrayList<>(temp)); //这个不能直接写成temp必须要写成new ArrayList
process(root, 0, 0, w - 1, res);
return res;
}
public int height(TreeNode root) {
if (root == null) return 0;
return Math.max(height(root.left), height(root.right)) + 1;
}
public void process(TreeNode root, int level, int l, int r, List<List<String>> res) {
if (root == null) return;
int m = l + (r - l) / 2;
res.get(level).set(m, String.valueOf(root.val));
process(root.left,level+1,l,m-1,res);
process(root.right,level+1,m+1,r,res);
}
或者使用二维字符矩阵:
public List<List<String>> printTree(TreeNode root) {
int height = height(root);
String[][] str = new String[height][(1 << height) - 1];
for(String[] arr:str) Arrays.fill(arr,"");
process(str, root, 0, 0, str[0].length);
List<List<String>> res = new ArrayList<>();
for(String[] arr:str) res.add(Arrays.asList(arr)); //asList()将一个数组转换成容器
return res;
}
public void process(String[][] res, TreeNode root, int level, int l, int r) {
if (root == null) return;
int m = l + (r - l)/2;
res[level][m] = "" + root.val;
process(res, root.left, level + 1, l, m-1);
process(res, root.right, level + 1, m+1, r);
}
public int height(TreeNode root) {
if (root == null) return 0;
return Math.max(height(root.left), height(root.right)) + 1;
}