Print Binary Tree
Thoughts
Code
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<string>> printTree(TreeNode* root) {
const auto h = height(root, 0), w = (int) pow(2, h) - 1;
vector<vector<string>> res(h, vector<string>(w, ""));
queue<pair<TreeNode*, pair<int, int>>> q;
q.push(make_pair(root, make_pair(0, w)));
int d = 0;
while (!q.empty()) {
int size = q.size();
for (int i = 0; i < size; ++i) {
const auto p = q.front(); q.pop();
const auto left = p.second.first;
const auto right = p.second.second;
const auto mid = left + (right - left) / 2;
res[d][mid] = to_string(p.first->val);
if (p.first->left) {
q.push(make_pair(p.first->left, make_pair(left, mid - 1)));
}
if (p.first->right) {
q.push(make_pair(p.first->right, make_pair(mid + 1, right)));
}
}
++d;
}
return res;
}
private:
int height(TreeNode* root, int h) {
if (!root) return h;
return max(height(root->left, h + 1), height(root->right, h + 1));
}
};Analysis
Previous987. Vertical Order Traversal of a Binary TreeNext267. Serialize and Deserialize Binary Tree
Last updated