Description
Print a binary tree in an m*n 2D string array following these rules:
- The row number m should be equal to the height of the given binary tree.
- The column number n should always be an odd number.
- The root node’s value (in string format) should be put in the exactly middle of the first row it can be put. The column and the row where the root node belongs will separate the rest space into two parts (left-bottom part and right-bottom part). You should print the left subtree in the left-bottom part and print the right subtree in the right-bottom part. The left-bottom part and the right-bottom part should have the same size. Even if one subtree is none while the other is not, you don’t need to print anything for the none subtree but still need to leave the space as large as that for the other subtree. However, if two subtrees are none, then you don’t need to leave space for both of them.
- Each unused space should contain an empty string “”.
- Print the subtrees following the same rules.
Example 1:
Input:
1
/
2
Output:
[["", "1", ""],
["2", "", ""]]
Example 2:
Input:
1
/ \
2 3
\
4
Output:
[["", "", "", "1", "", "", ""],
["", "2", "", "", "", "3", ""],
["", "", "4", "", "", "", ""]]
Example 3:
Input:
1
/ \
2 5
/
3
/
4
Output:
[["", "", "", "", "", "", "", "1", "", "", "", "", "", "", ""]
["", "", "", "2", "", "", "", "", "", "", "", "5", "", "", ""]
["", "3", "", "", "", "", "", "", "", "", "", "", "", "", ""]
["4", "", "", "", "", "", "", "", "", "", "", "", "", "", ""]]
Note: The height of binary tree is in the range of [1, 10].
问题描述
以m行, n列的二维字符串数组打印出二叉树, 遵守如下规则
- 行数m需要等于二叉树的高度
- 列数n需要为奇数
- 根节点的值(字符串形式)需要放在第一行的正中间。根节点处于的行和列会将剩余空间分成两部分, 左下和右下。你需要将左子树打印在左下部分, 将右子树打印在右下部分。左下部分和右下部分需要为同样大小。即使一个子树为空, 而另一个子树非空, 你需要为空子树的那一边与非空子树那边占用的同样大小的空间。然而, 若两个子树都为空, 你不需要为它们留空间。
- 每一个未使用的空间为空串”“
- 以同样的规则打印子树
问题分析
先通过后序遍历求出树的高度height, 也就是m, n = 2m−12m−1, 初始化res
然后通过前序遍历往res里面填充值, 注意start和end(用来取根节点所在位置), height(用来取所在行数)
解法
class Solution {
public List<List<String>> printTree(TreeNode root) {
List<List<String>> res = new ArrayList();
if(root == null) return res;
int height = getHeight(root);
int n = (1 << height) - 1;
List<String> line = new ArrayList();
for(int i = 0;i < n;i++) line.add("");
for(int i = 0;i < height;i++) res.add(new ArrayList(line));
preorder(root, res, 0, n, 0);
return res;
}
public void preorder(TreeNode root, List<List<String>> res, int start, int end, int depth){
if(root == null) return;
int mid = start + (end - start) / 2;
res.get(depth).set(mid, String.valueOf(root.val));
preorder(root.left, res, start, mid, depth + 1);
preorder(root.right, res, mid + 1, end, depth + 1);
}
public int getHeight(TreeNode root){
if(root == null) return 0;
return 1 + Math.max(getHeight(root.left), getHeight(root.right));
}
}