题目
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].
分析首先计算二叉树高度得到矩阵行数,然后根据最多节点个数计算矩阵列数,声明一个全为空字符串的res[m][n]矩阵,然后根据不同高度下各节点所在区间取中间值得到该节点放置位置。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void printBT(TreeNode* root,int beg,int end,int h,vector<vector<string>>& s){
s[h][(beg+end)/2]=to_string(root->val);//当前节点应放置在区间中间,利用(beg+end)/2找到索引位置
if(root->left!=NULL){
printBT(root->left,beg,(beg+end)/2-1,h+1,s);//分别构造左子树和右子树,增加层数
}
if(root->right!=NULL){
printBT(root->right,(beg+end)/2+1,end,h+1,s);
}
return ;
}
int heightBT(TreeNode* root){
if(root==NULL)
return 0;
int hl=heightBT(root->left)+1;
int hr=heightBT(root->right)+1;
return max(hl,hr);
}
vector<vector<string>> printTree(TreeNode* root) {
int height=heightBT(root);//首先计算二叉树的高度
int m=height,n=(1<<height)-1;//矩阵行数m等于二叉树高度,列数n等于2^m-1,利用位运算计算2^m次方
vector<vector<string>> res(m,vector<string>(n,""));//初始化结果矩阵,其中每行初始化为n个空字符串
res[0][n/2]=to_string(root->val);//对根节点进行构造,根节点在当前层数的区间的中间
if(root->left!=NULL){
printBT(root->left,0,n/2-1,1,res);//分别构造左子树和右子树,左子树在根节点左侧的区间,右子树在根节点右侧的区间
}
if(root->right!=NULL){
printBT(root->right,n/2+1,n-1,1,res);
}
return res;
}
};