leetcode_655. Print Binary Tree

https://leetcode.com/problems/print-binary-tree/

打印整棵二叉树

 

class Solution
{
public:

    int getTreeHeight(TreeNode* root)
    {
        return root==NULL?0:max(getTreeHeight(root->left), getTreeHeight(root->right))+1;
    }

    vector<vector<string>> printTree(TreeNode* root)
    {
        int height = getTreeHeight(root);
        vector<vector<string>> res(height, vector<string>((int)pow(2, height)-1,""));
        dfs(root, 0 , 0, pow(2, height)-1, res);
        return res;
    }

    void dfs(TreeNode* root, int layer, int l, int r, vector<vector<string>>& res)
    {
        if(root == NULL)
            return;
        int mid = (l+r)/2;
        stringstream ss;
        string value;
        ss<<root->val;
        ss>>value;
        res[layer][mid] = value;
        dfs(root->left, layer+1, l, mid-1, res);
        dfs(root->right, layer+1, mid+1, r, res);
    }
};

 

posted on 2019-04-12 11:30  JASONlee3  阅读(148)  评论(0编辑  收藏  举报

导航