问题分析
这个问题其实逻辑特别简单,就是找到应该打印的位置,然后打印上去就可以了。我这里直接使用递归的方式进行,保证了代码的整洁。按照题目要求高度至多10层,所以也不用考虑太多的效率问题。
代码
class Solution {
public:
int treeHeight(TreeNode *root){
if(root == NULL)
return 0;
return max(treeHeight(root->left), treeHeight(root->right)) + 1;
}
void printRoot(TreeNode *root,int height, int left, int right, vector<vector<string>> &board){
if(root == NULL)
return;
int mid = (left + right) / 2;
board[height][mid] = to_string(root->val);
printRoot(root->left, height + 1, left, mid - 1, board);
printRoot(root->right, height + 1, mid + 1, right, board);
}
vector<vector<string>> printTree(TreeNode* root){
int treeheight = treeHeight(root);
vector<vector<string>> board(treeheight, vector<string>(pow(2, treeheight) - 1,""));
printRoot(root, 0, 0, pow(2, treeheight) - 2, board);
return board;
}
};