题目
测试用例
root = [1,2]
root = [1,2,3,null,4]
思路
没什么思路,拉哥们一起做的,哥们负责思考,我负责鼓掌。
根据题目中给的矩阵的规则,第三第四条可以看出是让通过预先构造一个都是“”的矩阵,然后通过在指定位置放置二叉树内容的方式得到矩阵,而不是直接输出矩阵。而且位置的坐标公式都给了出来,那么目标就转换成求公式中的变量。
- 首先要在指定位置放置数字的前提是获取到指定的数字。那么第一步就是根据给的root遍历二叉树得到一个二维数组,数组内容分别是二叉树中每一层的内容。
- 然后根据题目提示的坐标将遍历得到的数组内容放入到指定的位置。
代码尝试
@Test
void printTree(){
//二叉树高度
//每一行创建linkedList,
TreeNode root = new TreeNode(1, new TreeNode(2, null, new TreeNode(4)), new TreeNode(3));
List<List<String>> list = new ArrayList<>();
fun(list, 0, root);
list.remove(list.size() - 1);
int nL = (1 << list.size()) - 1;
List<List<String>> result = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
List<String> m = new ArrayList<>();
result.add(m);
for (int j = 0; j < nL; j++) {
m.add("");
}
}
System.out.println(list);
fun2(result, 0, (nL - 1) / 2, root, list.size());
System.out.println(result);
}
// 将其左子节点放置在 res[r+1][c-2height-r-1] ,
// 右子节点放置在 res[r+1][c+2height-r-1] 。
void fun2(List<List<String>> result, int r, int c, TreeNode root,int height) {
if (root == null) {
return;
}
int i = 1 << (height - r - 2);
result.get(r).set(c, root.val+"");
fun2(result, r + 1, c - i, root.left, height);
fun2(result, r + 1, c + i, root.right, height);
}
void fun(List<List<String>> list, int deep, TreeNode node) {
if (list.size() <= deep) {
list.add(new ArrayList<>());
}
List<String> integers = list.get(deep);
if (node == null) {
integers.add("");
return;
}
integers.add(node.val+"");
fun(list, deep + 1, node.left);
fun(list, deep + 1, node.right);
}
解法主要来自朋友😭