forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path655.Print-Binary-Tree.cpp
36 lines (33 loc) · 1.01 KB
/
655.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
/**
* 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)
{
int maxHeight = getHeight(root);
int maxWidth = pow(2,maxHeight)-1;
auto results=vector<vector<string>>(maxHeight,vector<string>(maxWidth));
DFS(root,0,0,maxWidth-1,results);
return results;
}
void DFS(TreeNode* root, int dep, int start, int end, vector<vector<string>>& results)
{
if (root==NULL) return;
int pos=(start+end)/2;
results[dep][pos]=to_string(root->val);
DFS(root->left,dep+1,start,pos-1,results);
DFS(root->right,dep+1,pos+1,end,results);
}
int getHeight(TreeNode* root)
{
if (root==NULL) return 0;
else return max(getHeight(root->left),getHeight(root->right))+1;
}
};