Print Binary Tree
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.
解析
解法1:递归
首先建立一个计算出二叉树的高度h,以及应有的节点位置数w,w=2h -1,建立一个h*w的数组,初始化为空字符串。
递归在每一层的中间位置插入层的值。
class Solution {
public:
vector<vector<string>> printTree(TreeNode* root) {
int h = getHight(root);
int w = pow(2,h)-1;
vector<vector<string>> res(h, vector<string>(w, ""));
helper(root, 0, w-1,0, h, res);
return res;
}
void helper(TreeNode* node, int i, int j, int curh, int height, vector<vector<string>>& res){
if(!node || curh == height) return;
res[curh][(i+j)/2] = to_string(node->val);
helper(node->left, i, (i+j)/2-1, curh+1, height, res);
helper(node->right, (i+j)/2+1, j, curh+1, height, res);
}
int getHight(TreeNode* root){
if(!root) return 0;
return 1 + max(getHight(root->left), getHight(root->right));
}
};
解法2:迭代
利用层序遍历,构建两个队列,一个存储节点,一个存储当前的起始位置和终止位置,即一个pair对象。
class Solution {
public:
vector<vector<string>> printTree(TreeNode* root) {
int h = getHight(root);
int w = pow(2,h)-1;
int curH = -1;
vector<vector<string>> res(h, vector<string>(w, ""));
queue<TreeNode*> node;
node.push(root);
queue<pair<int,int>> index;
index.push({0, w-1});
while(!node.empty()){
int size = node.size();
curH ++;
for(int i=0;i<size;i++){
TreeNode* p = node.front();
node.pop();
pair<int,int> ind = index.front();
index.pop();
int left = ind.first, right = ind.second;
int mid = (right+left)/2;
res[curH][mid] = to_string(p->val);
if(p->left){
node.push(p->left);
index.push({left, mid-1});
}
if(p->right){
node.push(p->right);
index.push({mid+1, right});
}
}
}
return res;
}
int getHight(TreeNode* root){
if(!root) return 0;
return 1 + max(getHight(root->left), getHight(root->right));
}
};