Wednesday, October 4, 2017

655. Print Binary Tree

https://leetcode.com/problems/print-binary-tree/description/
Solution 1. Always think in the computer way. Figure out the repeating pattern.
    int height(TreeNode* node) {
        if(!node) return 0;
        int l = height(node->left), r = height(node->right);
        return max(l, r) + 1;
    }
    int width(TreeNode* node) {
        if(!node) return 0;
        int l = width(node->left), r = width(node->right);
        return max(l, r) * 2 + 1;
    }
    void print(TreeNode* node, vector<vector<string>>& res, int level, int l, int r) {
        if(!node) return;
        int mid = l + (r - l)/2;
        res[level][mid] = to_string(node->val);
        print(node->left, res, level+1, l, mid-1);
        print(node->right, res, level+1, mid+1, r);
    }
    vector<vector<string>> printTree(TreeNode* root) {
        int h = height(root);
        //int w = pow(2,h) - 1;
        int w = width(root);
        vector<vector<string>> res(h, vector<string> (w,""));
        print(root, res, 0, 0, w-1);
        return res;
    }
Solution 2. Convert location to index.
    void visit(TreeNode* node, vector<vector<pair<int,int>>>& t, int level, int idx) {
        if(!node) return;
        if(t.size()==level) t.push_back({});
        t[level].push_back({idx, node->val});
        visit(node->left, t, level+1, 2*idx);
        visit(node->right, t, level+1, 2*idx+1);
    }
    vector<vector<string>> printTree(TreeNode* root) {
        vector<vector<pair<int,int>>> t;
        visit(root, t, 0, 0);
        int r = t.size();
        int c = pow(2,r) - 1;
        vector<vector<string>> res(r, vector<string> (c, ""));

        for(int i=r-1; i>=0; i--) {
            int k0 = pow(2, r-i-1) - 1;
            int dk = pow(2, r-i);
            for(int j=0; j<t[i].size(); j++) {
                int k = k0 + dk*t[i][j].first;
                res[i][k] = to_string(t[i][j].second);
            }
        }
        return res;
    }

No comments:

Post a Comment