Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * 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 {
- public:
- int maxdepth(TreeNode* root){
- if(root==nullptr){
- return 0;
- }
- return max(1+maxdepth(root->left),1+maxdepth(root->right));
- }
- void dfs(TreeNode* root,vector<vector<string>>& ans,int i,int j,int depth){
- if(root==nullptr){
- return;
- }
- depth--;
- ans[i][j]=to_string(root->val);
- if(i+1<ans.size()){
- dfs(root->left,ans,i+1,j-depth-1,depth);
- dfs(root->right,ans,i+1,j+depth+1,depth);
- }
- return;
- }
- vector<vector<string>> printTree(TreeNode* root) {
- vector<vector<string>> ans;
- int depth=maxdepth(root);
- cout<<depth<<endl;
- for(int i=0;i<depth;i++){
- vector<string> temp;
- for(int j=0;j<pow(2,depth)-1;j++){
- temp.push_back("");
- }
- ans.push_back(temp);
- }
- dfs(root,ans,0,depth+depth%2-1,depth-1);
- return ans;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement