码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_655. Print Binary Tree

时间:2019-04-12 11:51:41      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:com   font   href   tco   color   roo   max   .com   ros   

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);
    }
};

 

leetcode_655. Print Binary Tree

标签:com   font   href   tco   color   roo   max   .com   ros   

原文地址:https://www.cnblogs.com/jasonlixuetao/p/10694984.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!