Leetcode 655. Print Binary Tree
(Directly from Leetcode)
You need to print the binary tree in a 2-D array in reverse order. Here are the steps to do that:
r
should be equal to the height of the tree.c
should be equal to 2^h - 1
- where h
is the height of the tree.0
).nd
at position (r, c)
, you should assign its left child to the position (r+1, c - 2^(h-r-1))
and the right child to (r+1, c + 2^(h-r-1))
.""
for null nodes.""
), having the specified dimensions.result
of dimensions h x (2^h - 1)
filled with empty strings.#include <vector>
#include <string>
#include <cmath>
#include <algorithm>
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
int getHeight(TreeNode* root) {
if (!root) return 0;
return 1 + std::max(getHeight(root->left), getHeight(root->right));
}
void fill(TreeNode* root, std::vector<std::vector<std::string>>& res, int r, int c, int height) {
if (!root) return;
res[r][c] = std::to_string(root->val);
// Calculate midpoint offset for the next level
int offset = std::pow(2, height - r - 1);
if (root->left) fill(root->left, res, r + 1, c - offset, height);
if (root->right) fill(root->right, res, r + 1, c + offset, height);
}
std::vector<std::vector<std::string>> printTree(TreeNode* root) {
int height = getHeight(root);
int width = std::pow(2, height) - 1;
std::vector<std::vector<std::string>> res(height, std::vector<std::string>(width, ""));
fill(root, res, 0, (width - 1) / 2, height);
return res;
}
};
O(N)
, where N
is the number of nodes in the tree (in the worst case, we visit each node once).O(N)
, as we also visit each node exactly once to place it in the correct position.Thus, the overall time complexity is O(N)
.
h x (2^h - 1)
, where h
is the height of the tree.h
.Thus, the overall space complexity is O(h * 2^h)
, which simplifies to O(N)
in terms of tree nodes if we consider a complete binary tree structure.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?