DFS
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int getDeep(TreeNode* root, int n){
// 获取深度
if(!root) return n;
return max(getDeep(root->left, n+1), getDeep(root->right, n+1));
}
vector<vector<string>> printTreeHelp(TreeNode* root, int deep, int level) {
// deep 表示整个树深度, level表示当前深度为第几层
vector<vector<string>> ans;
if(level == deep) return ans; // 递归到最大深度
vector<string> top;
ans.push_back(top);
string val;
if(!root){ // 若当前节点为空,则值为空即可
root = new TreeNode;
val = "";
}
else val = to_string(root->val);
vector<vector<string>> left = printTreeHelp(root->left, deep, level + 1);
vector<vector<string>> right = printTreeHelp(root->right, deep, level + 1);
int i = 0;
// 拼凑左右子树数组
for(; i < min(left.size(),right.size()); i++){
vector<string> temp(left[i]); // 直接用左子树的该行数组初始化
temp.push_back(""); // 拼凑时记得root这一列都有空字符串
for(int j = 0; j < right[i].size(); j++){
temp.push_back(right[i][j]);
}
ans.push_back(temp);
}
// 生成root节点的数组
if(level == deep-1){ // 是最底层了,无子节点,直接返回
ans[0].push_back(val);
return ans;
}
for(int i = 0; i < ans[1].size(); i++){
ans[0].push_back("");
}
ans[0][ans[1].size()/2] = val;
return ans;
}
vector<vector<string>> printTree(TreeNode* root) {
int deep = getDeep(root, 0);
vector<vector<string>> ans;
return printTreeHelp(root, deep, 0);
}
};