[LeetCode] Print Binary Tree

655. Print Binary Tree

Given the root of a binary tree, construct a 0-indexed m x n string matrix res that represents a formatted layout of the tree. The formatted layout matrix should be constructed using the following rules:

  • The height of the tree is height and the number of rows m should be equal to height + 1.
  • The number of columns n should be equal to 2height+1 - 1.
  • Place the root node in the middle of the top row (more formally, at location res[0][(n-1)/2]).
  • For each node that has been placed in the matrix at position res[r][c], place its left child at res[r+1][c-2height-r-1] and its right child at res[r+1][c+2height-r-1].
  • Continue this process until all the nodes in the tree have been placed.
  • Any empty cells should contain the empty string “”.

Return the constructed matrix res.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
vector<vector<string>> res;
int maxDepth(TreeNode* node) {
if(!node) return 0;
return max(maxDepth(node->left), maxDepth(node->right)) + 1;
}
void dfs(TreeNode* node, int l, int r, int level = 0) {
if(!node) return;
int m = l + (r - l) / 2;
dfs(node->left, l, m - 1, level + 1);
res[level][m] = to_string(node->val);
dfs(node->right, m + 1, r, level + 1);
}
public:
vector<vector<string>> printTree(TreeNode* root) {
int h = maxDepth(root), pos = 0;
res = vector<vector<string>>(h, vector<string>(pow(2,h) - 1));
dfs(root, 0, pow(2,h) - 2);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/07/PS/LeetCode/print-binary-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.