携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第24天,点击查看活动详情
痛苦周一,真的难顶,偏偏任务量还超多
输出二叉树
该题出自力扣的655题 —— 输出二叉树【中等题】
审题
- 该题的题意并不复杂,甚至把解法都写在题目里面了,只需要转化成代码形式即可
- 给出一个二叉树,需要返回二叉树的列表形式,也就是视觉上的列表
- 直接模拟解法即可
- 题目需要给出树的高度height
- 这里使用dfs(深度遍历)的方法去获取,直接递归获得最深的高度
- 因此通过高度获得矩阵的行数,因为是从0开始的下标,所以行数是高度加一
- 列数的2的行数次方 减一
- 根节点的特殊性,所以单独出黎,放在列数 减一余2的位置
- 实际解法中,用了广度遍历二叉树
- 封装了一套数据结构,因为二叉树的节点之间,有一层列表下标的关系
- 题目需要给出树的高度height
编码
class Solution {
public List<List<String>> printTree(TreeNode root) {
int max = dfs(root,0);
int n = (1 << (max)) - 1;
List<List<String>> lists = createNullList(max,n);
//层序
Queue<HelperTreeNode> queue = new LinkedList<>();
int column = (n - 1) >> 1;
queue.offer(new HelperTreeNode(root,0,column));
while (!queue.isEmpty()){
int size = queue.size();
for (int i = 0; i < size; i++) {
HelperTreeNode h = queue.poll();
TreeNode poll = h.treeNode;
int row = h.row;
int column1 = h.column;
lists.get(h.row).set(column1, String.valueOf(poll.val));
if (poll.left != null){
queue.offer(new HelperTreeNode(poll.left,row +1,column1-(1<< (max - 2 -row))));
}
if (poll.right != null){
queue.offer(new HelperTreeNode(poll.right,row +1,column1+(1<< (max - 2 -row))));
}
}
}
return lists;
}
private List<List<String>> createNullList(int m, int n) {
List<List<String>> list = new ArrayList<>();
for (int i = 0; i < m; i++) {
List<String> temp = new ArrayList<>();
for (int j = 0; j < n; j++) {
temp.add("");
}
list.add(temp);
}
return list;
}
public int dfs(TreeNode root,int i){
if (root == null){
return i;
}
i++;
System.out.println(root.val);
int left = dfs(root.left,i);
int right = dfs(root.right,i);
return Math.max(left,right);
}
class HelperTreeNode {
TreeNode treeNode;
int row;
int column;
public HelperTreeNode(TreeNode treeNode) {
this.treeNode = treeNode;
}
public HelperTreeNode(TreeNode treeNode, int row, int column) {
this.treeNode = treeNode;
this.row = row;
this.column = column;
}
}
}