simple DFS solution with c++


  • 0
    J

    get the depth first and the matric width is 2^depth-1,initialize the matric with "",then replace the value at the right place

    class Solution {
    public:
    int get_depth(TreeNode* root){
    if(root==nullptr)
    return 0;
    else
    return 1+max(get_depth(root->left),get_depth(root->right));
    }
    void dfs_print(vector<vector<string>> &re,TreeNode* root,int l,int r,int level){
    int mid = (l+r)/2;
    if(root){
    re[level][mid] = to_string(root->val);
    dfs_print(re,root->left,l,mid-1,level+1);
    dfs_print(re,root->right,mid+1,r,level+1);
    }
    }
    vector<vector<string>> printTree(TreeNode* root) {//先求出深度,宽度,初始化字符矩阵,最后递归的更改有结点的地方
    int h = get_depth(root);
    int w = pow(2,h)-1;
    vector<vector<string>> re(h,vector<string>(w,""));
    dfs_print(re,root,0,w-1,0);
    return re;
    }
    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.