forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
print-binary-tree.cpp
46 lines (42 loc) · 1.25 KB
/
print-binary-tree.cpp
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// Time: O(h * 2^h)
// Space: O(h * 2^h)
/**
* 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) {
auto h = getHeight(root), w = getWidth(root);
vector<vector<string>> result(h, vector<string>(w, ""));
preorderTraversal(root, 0, 0, w - 1, &result);
return result;
}
private:
int getHeight(TreeNode* root) {
if (!root) {
return 0;
}
return max(getHeight(root->left), getHeight(root->right)) + 1;
}
int getWidth(TreeNode* root) {
if (!root) {
return 0;
}
return 2 * max(getWidth(root->left), getWidth(root->right)) + 1;
}
void preorderTraversal(TreeNode *root, int level, int left, int right, vector<vector<string>> *result) {
if (!root) {
return;
}
auto mid = left + (right - left) / 2;
(*result)[level][mid] = to_string(root->val);
preorderTraversal(root->left, level + 1, left, mid - 1, result);
preorderTraversal(root->right, level + 1, mid + 1, right, result);
}
};