zoukankan      html  css  js  c++  java
  • 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);
        }
    };
  • 相关阅读:
    Heavy Transportation POJ
    Frogger POJ
    CODEFORCES 25E Test
    POJ
    POJ-2777
    [ZJOI2008]骑士
    POJ
    POJ
    [USACO12FEB]Nearby Cows
    [HAOI2009]毛毛虫
  • 原文地址:https://www.cnblogs.com/jasonlixuetao/p/10694984.html
Copyright © 2011-2022 走看看