Skip to content

Commit 246bf60

Browse files
authored
Create 655.Print-Binary-Tree.cpp
1 parent b8528e5 commit 246bf60

1 file changed

Lines changed: 36 additions & 0 deletions

File tree

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8+
* };
9+
*/
10+
class Solution {
11+
public:
12+
vector<vector<string>> printTree(TreeNode* root)
13+
{
14+
int maxHeight = getHeight(root);
15+
int maxWidth = pow(2,maxHeight)-1;
16+
auto results=vector<vector<string>>(maxHeight,vector<string>(maxWidth));
17+
DFS(root,0,0,maxWidth-1,results);
18+
return results;
19+
}
20+
21+
void DFS(TreeNode* root, int dep, int start, int end, vector<vector<string>>& results)
22+
{
23+
if (root==NULL) return;
24+
int pos=(start+end)/2;
25+
results[dep][pos]=to_string(root->val);
26+
DFS(root->left,dep+1,start,pos-1,results);
27+
DFS(root->right,dep+1,pos+1,end,results);
28+
}
29+
30+
int getHeight(TreeNode* root)
31+
{
32+
if (root==NULL) return 0;
33+
else return max(getHeight(root->left),getHeight(root->right))+1;
34+
}
35+
36+
};

0 commit comments

Comments
 (0)