leetcode_655. Print Binary Tree

Posted jasonlixuetao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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);
    }
};

 

以上是关于leetcode_655. Print Binary Tree的主要内容,如果未能解决你的问题,请参考以下文章

leetcode算法:Trim a Binar Search Tree

655. Print Binary Tree 解题报告(树)

LC 655. Print Binary Tree

leetcode -day23 Construct Binary Tree from Inorder and Postorder Traversal &amp; Construct Binar

655.Print Binary Tree 打印二叉树

Leetcode 655.输出二叉树