题目描述
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", "", ""]]
题意:在一个 m*n 的二维字符串数组中输出二叉树,并遵守以下规则:
- 行数 m 应当等于给定二叉树的高度。
- 列数 n 应当总是奇数。
- 根节点的值(以字符串格式给出)应当放在可放置的第一行正中间。根节点所在的行与列会将剩余空间划分为两部分(左下部分和右下部分)。
- 你应该将左子树输出在左下部分,右子树输出在右下部分。左下和右下部分应当有相同的大小。即使一个子树为空而另一个非空,你不需要为空的子树输出任何东西,但仍需要为另一个子树留出足够的空间。然而,如果两个子树都为空则不需要为它们留出任何空间。
- 每个未使用的空间应包含一个空的字符串”“。
- 使用相同的规则输出子树。
算法1
(递归)
题解:题目已经很清楚需要使用递归,首先我们需要知道整个打印空间的高度和宽度。因为根节点需要打印在中间。所以我们能够得到:
$H = max(H_{left},H_{right}) + 1$
$W = 2 * max(W_{left},W_{right}) + 1$
打印的时候,先打印根节点,然后递归打印左右子树。
C++ 代码
class Solution {
public:
vector<vector<string>> printTree(TreeNode* root) {
auto t = getWidth(root);
int depth = t.first,width = t.second;
vector<vector<string>> res(depth,vector<string>(width,""));
print(root,0,width - 1,0,res);
return res;
}
pair<int,int> getWidth(TreeNode* root)
{
if(root == NULL)
return make_pair(0,0);
auto left = getWidth(root->left);
auto right = getWidth(root->right);
return make_pair(max(left.first,right.first) + 1,2 * max(left.second,right.second) + 1);
}
// left、right代表当前打印空间的左右范围,level代表根节点打印在第几层,mid = (left + right) / 2代表根节点打印在第几列
void print(TreeNode* root,int left,int right,int level,vector<vector<string>> &res)
{
if(root == NULL)
return;
int mid = (left + right) / 2;
res[level][mid] = to_string(root->val);
print(root->left,left,mid - 1,level + 1,res);
print(root->right,mid + 1,right,level + 1,res);
}
};