leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0655.cpp (797B)


      1 class Solution {
      2     int height(const TreeNode *root) {
      3         if (!root) return 0;
      4         return 1 + max(height(root->left), height(root->right));
      5     }
      6 
      7     typedef tuple<TreeNode *, int, int> record;
      8 
      9   public:
     10     vector<vector<string>> printTree(TreeNode *root) {
     11         const int n = height(root), m = (1 << n) - 1;
     12         vector<vector<string>> res(n, vector<string>(m));
     13 
     14         queue<record> q;
     15         q.push({root, 0, (m - 1) / 2});
     16         while (!q.empty()) {
     17             const auto [root, r, c] = q.front();
     18             q.pop();
     19             res[r][c] = to_string(root->val);
     20             if (root->left) q.push({root->left, r + 1, c - (1 << (n - r - 2))});
     21             if (root->right) q.push({root->right, r + 1, c + (1 << (n - r - 2))});
     22         }
     23         return res;
     24     }
     25 };