题目
给你一棵二叉树的根节点 root ,请你构造一个下标从 0 开始、大小为 m x n 的字符串矩阵 res ,用以表示树的 格式化布局 。构造此格式化布局矩阵需要遵循以下规则:
树的 高度 为 height ,矩阵的行数 m 应该等于 height + 1 。
矩阵的列数 n 应该等于 2height+1 - 1 。
根节点 需要放置在 顶行 的 正中间 ,对应位置为 res[0][(n-1)/2] 。
对于放置在矩阵中的每个节点,设对应位置为 res[r][c] ,将其左子节点放置在 res[r+1][c-2height-r-1] ,右子节点放置在 res[r+1][c+2height-r-1] 。
继续这一过程,直到树中的所有节点都妥善放置。
任意空单元格都应该包含空字符串 "" 。
返回构造得到的矩阵 res 。
来源:力扣(LeetCode)
方法:深度优先搜索
思路与算法:我们可以通过深度优先搜索来解决此题。首先通过深度优先搜索来得到二叉树的高度 height(注意高度从 00 开始),然后创建一个行数为 m = height + 1m=height+1,列数为 n = 2^height + 1} - 1 n=2^(height+1)−1 的答案数组 res放置节点的值(字符串形式)。根节点的值应当放在当前空间的第一行正中间。根节点所在的行与列会将剩余空间划分为两部分(左下部分和右下部分),然后递归地将左子树输出在左下部分空间,右子树输出在右下部分空间即可。
public class Solution_655 {
public static void main(String[] args) {
TreeNode root = new TreeNode(5,new TreeNode(3,new TreeNode(2),new TreeNode(4)),new TreeNode(6,null ,new TreeNode(7)));
System.out.println(new Solution_655().printTree(root));
}
List<List<String>> result = new ArrayList<>();
int treeHeight =1;
public List<List<String>> printTree(TreeNode root) {
// 获取树的高度
height(root,treeHeight);
// 创建矩阵
for (int i = 0; i < treeHeight; i++) {
List<String> nodes = new ArrayList<>();
for (int j = 1; j <= Math.pow(2, treeHeight) - 1; j++) {
nodes.add("");
}
result.add(nodes);
}
// 给矩阵填入数据
setNodeValue(root, 0, (int) (Math.pow(2, treeHeight - 1) - 1));
return result;
}
void height(TreeNode root, int currentHeight){
if (root==null){
return;
}
if (treeHeight<currentHeight){
treeHeight =currentHeight;
}
currentHeight+=1;
height(root.left,currentHeight);
height(root.right,currentHeight);
}
private void setNodeValue(TreeNode root, int y, int x) {
if (root == null) {
return;
}
result.get(y).set(x, String.valueOf(root.val));
setNodeValue(root.left, y + 1, (int) (x - Math.pow(2, treeHeight - 1 - y - 1)));
setNodeValue(root.right, y + 1, (int) (x + Math.pow(2, treeHeight - 1 - y - 1)));
}}/**
* Definition for a binary tree node.
*/class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}}
复杂度分析
时间复杂:O(height} 2^height})O(height×2height),其中 height 是二叉树的高度。需要填充 (height + 1) (2^{height +1}-1(height+1)×(2height+1 −1)的数组。
空间复杂度:O(height)O(height),其中 height是二叉树的高度。空间复杂度主要是递归调用的栈空间,取决于二叉树的高度。注意返回值不计入空间复杂度。
出现的错误:
void height(TreeNode root, int currentHeight){
if (root.left!=null){
currentHeight +=1;
height(root.left, currentHeight);
}else {
if (currentHeight >treeHeight){
treeHeight= currentHeight;
}
}
if (root.right!=null){
currentHeight +=1;
height(root.right, currentHeight);
}else {
if (currentHeight >treeHeight){
treeHeight= currentHeight;
}
}
}
height方法在左节点遍历结束后将左节点的高度加上了右节点的高度导致树的高度异常
修复:
void height(TreeNode root, int currentHeight){
if (root==null){
return;
}
if (treeHeight<currentHeight){
treeHeight =currentHeight;
}
currentHeight+=1;
height(root.left,currentHeight);
height(root.right,currentHeight);
}